我通过编译时编织使用Spring和AspectJ,对非容器管理的对象使用@Configurable注释。
下面是一个@Configurable注释对象示例:
@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;
}
}组件,将其插入到此对象中:
@Component
public class TestComponent {}当我在创建上下文之后创建TestConfigurable时,TestComponent可以很好地注入到那里,但是当我通过@PostConstruct注释的方法这样做时,自动装配就不会发生了。
组件具有@PostConstruct:
@Component
public class TestPostConstruct {
@PostConstruct
public void initialize() {
TestConfigurable configurable = new TestConfigurable();
System.out.println("In post construct: " + configurable.getComponent());
}
}我正在执行的应用程序:
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());
}
}下面是应用程序产生的输出:
In post construct: null
After context is loaded: paulenka.aleh.roguelike.sandbox.TestComponent@fe18270那么,有什么解决办法可以将依赖项注入到@PostConstruct方法中创建的@Configurable对象中吗? All @Component注释bean已经在上下文中,并且在调用@PostConstruct时已经为它们完成了自动装配。为什么春天不在这里做自动装配?
如果能够帮助解决问题,可以发布其他配置文件(上下文和pom.xml)。
更新1:似乎找到了问题的原因。带有@Configurable注释的对象由实现AnnotationBeanConfigurerAspect的BeanFactoryAware初始化。这个方面使用BeanFactory初始化bean。看起来,TestPostConstruct对象的@PostConstruct方法是在BeanFactory设置为AnnotationBeanConfigurerAspect之前执行的。如果将记录器设置为调试,则将下列消息打印到控制台:"BeanFactory尚未设置.:确保此配置器在Spring容器中运行。无法配置类型为.的bean,不需要注入。“
如果有什么解决办法的话我还没解决.
发布于 2014-12-02 08:21:08
我找到了一个解决办法。要在执行@PostConstruct之前初始化AnnotationBeanConfigurerAspect方面,可以使用以下@PostConstruct方法向类添加以下注释:
@DependsOn("org.springframework.context.config.internalBeanConfigurerAspect")希望这些信息对某些人有帮助。
发布于 2021-09-24 18:05:18
我想,你忘了添加@EnableSpringConfigured。您必须使用此注释。
https://stackoverflow.com/questions/27230446
复制相似问题