2016-10-28 37 views
3

我動態地添加上下文來用下面的代碼的應用程序上下文:動力方面 - 自動裝配

@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爲空。

有沒有辦法在創建bean時強制自動裝配發生?我希望ctx.refresh()能做到這一點。

回答

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> 
+0

This works great。謝謝! – alan