我通過(guò)編譯時(shí)編織將Spring與AspectJ結(jié)合使用,以便對(duì)不受容器管理的對(duì)象使用@Configurable spring注釋. 這是一個(gè)@Configurable注釋的對(duì)象示例: @Configurable(autowire = Autowire.BY_TYPE)
public class TestConfigurable {
private TestComponent component;
public TestComponent getComponent() {
return component;
}
@Autowired
public void setComponent(TestComponent component) {
this.component = component;
}
}
我要注入此對(duì)象的組件: @Component
public class TestComponent {}
當(dāng)我在創(chuàng)建上下文之后創(chuàng)建TestConfigurable時(shí),可以很好地注入TestComponent,但是當(dāng)我從@ PostConstruct-annotated方法執(zhí)行此操作時(shí),不會(huì)自動(dòng)裝配. 具有@PostConstruct的組件: @Component
public class TestPostConstruct {
@PostConstruct
public void initialize() {
TestConfigurable configurable = new TestConfigurable();
System.out.println("In post construct: " configurable.getComponent());
}
}
我正在執(zhí)行的應(yīng)用程序: public class TestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
applicationContext.registerShutdownHook();
TestConfigurable configurable = new TestConfigurable();
System.out.println("After context is loaded: " configurable.getComponent());
}
}
這是此應(yīng)用程序產(chǎn)生的輸出: In post construct: null
After context is loaded: paulenka.aleh.roguelike.sandbox.TestComponent@fe18270
那么,有什么解決方法可以將依賴項(xiàng)注入到@PostConstruct方法內(nèi)部創(chuàng)建的@Configurable對(duì)象中?所有帶有@Component注釋的Bean都已存在于上下文中,并且在調(diào)用@PostConstruct時(shí)已為它們自動(dòng)完成了裝配.為什么Spring在這里不自動(dòng)布線? 可以發(fā)布其他配置文件(上下文和pom.xml),如果它們有助于解決問(wèn)題. 更新1: 看起來(lái)我找到了問(wèn)題的原因.用@Configurable注釋的對(duì)象由實(shí)現(xiàn)BeanFactoryAware的AnnotationBeanConfigurerAspect初始化.該方面使用BeanFactory初始化bean.看起來(lái)在BeanFactory設(shè)置為AnnotationBeanConfigurerAspect之前,已執(zhí)行TestPostConstruct對(duì)象的@PostConstruct方法.如果設(shè)置為調(diào)試的記錄器將以下消息打印到控制臺(tái):“尚未在…上設(shè)置BeanFactory:確保此配置程序在Spring容器中運(yùn)行.無(wú)法配置類型[…]的Bean.繼續(xù)進(jìn)行操作,無(wú)需注入. ”
是否有任何解決方法的問(wèn)題仍對(duì)我開放… 解決方法: 我找到了一種解決方法.要在執(zhí)行@PostConstruct之前初始化AnnotationBeanConfigurerAspect方面,可以使用此類@PostConstruct方法將以下注釋添加到類中: @DependsOn("org.springframework.context.config.internalBeanConfigurerAspect")
希望這些信息對(duì)某人有用. 來(lái)源:https://www./content-4-531501.html
|