动态上下文 - 自动装配

时间:2016-10-28 16:08:20

标签: spring spring-integration

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

@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为:

<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()会这样做。

1 个答案:

答案 0 :(得分:3)

这对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>