gpt4 book ai didi

spring - 动态上下文 - Autowiring

转载 作者:行者123 更新时间:2023-12-02 07:04:17 25 4
gpt4 key购买 nike

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

@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"/>

具有以下 Autowiring :

public class ContractMapper implements RowMapper<ContractFile> {

@Autowired
IIntegrationDao integrationDao;

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

在运行时,outboundContractJdbcFileMapper 属性integrationDao 为空。

有没有办法在创建 Bean 时强制进行 Autowiring ?我希望 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 - 动态上下文 - Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com