其他分享
首页 > 其他分享> > 弹簧-动态上下文-自动装配

弹簧-动态上下文-自动装配

作者:互联网

我使用以下代码将上下文动态添加到应用程序上下文中:

@Component
@Scope("singleton")
public class DynamicContextLoader implements ApplicationContextAware {

   private static ApplicationContext context;

   private Map<String, InterfacePropertyDto> contextMap;

   @Autowired
   IJpaDao jpaDao;

   @PostConstruct
   public void init() {
      contextMap = (Map<String, InterfacePropertyDto>) context.getBean("contextMap");
      contextMap.forEach((contextName, property) -> {
         String p = jpaDao.getProperty(property.getPropertyName(), property.getPropertyType());
         if (p != null) {
            ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
                    new String[]{"/META-INF/spring/integration/" + contextName},
                    false, context);
            ctx.refresh();
         }
      });


   }

   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      context = applicationContext;
   }
}

这很好用,并且创建了在新上下文中定义的所有bean.但是,@ Autowired不适用于任何这些新bean.

例如,在新上下文中定义为:

<bean id="outboundContractJdbcFileMapper" class="com.......integration.model.contract.ContractMapper"/>

具有以下自动装配:

public class ContractMapper implements RowMapper<ContractFile> {

   @Autowired
   IIntegrationDao integrationDao;

   @Override
   public ContractFile mapRow(ResultSet rs, int rowNum) throws SQLException {
      ......
   }
}

在运行时,outboundContractJdbcFileMapper属性IntegrationDao为null.

有没有办法在创建bean时强制进行自动装配?我希望ctx.refresh()能做到这一点.

解决方法:

这不适用于ClassPathXmlApplicationContext.您必须添加< context:annotation-config />也针对该子上下文:

<xsd:element name="annotation-config">
    <xsd:annotation>
        <xsd:documentation><![CDATA[
Activates various annotations to be detected in bean classes: Spring's @Required and
@Autowired, as well as JSR 250's @PostConstruct, @PreDestroy and @Resource (if available),
JAX-WS's @WebServiceRef (if available), EJB 3's @EJB (if available), and JPA's
@PersistenceContext and @PersistenceUnit (if available). Alternatively, you may
choose to activate the individual BeanPostProcessors for those annotations.

Note: This tag does not activate processing of Spring's @Transactional or EJB 3's
@TransactionAttribute annotation. Consider the use of the <tx:annotation-driven>
tag for that purpose.

See javadoc for org.springframework.context.annotation.AnnotationConfigApplicationContext
for information on code-based alternatives to bootstrapping annotation-driven support.
        ]]></xsd:documentation>
    </xsd:annotation>
</xsd:element>

标签:spring,spring-integration
来源: https://codeday.me/bug/20191118/2024953.html