我通过编译时编织将Spring与AspectJ结合使用,以将@Configurable spring注释用于不受容器管理的对象。
这是一个@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-annotated方法执行此操作时,不会自动装配。
具有@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对象中?所有带有@Component注释的Bean都已存在于上下文中,并且在调用@PostConstruct时已为它们自动完成了装配。为什么Spring在这里不自动布线?
可以发布其他配置文件(上下文和pom.xml),如果它们有助于解决问题。
更新1: 看起来我找到了问题的原因。用@Configurable注释的对象由实现BeanFactoryAware的AnnotationBeanConfigurerAspect初始化。该方面使用BeanFactory初始化bean。看起来在BeanFactory设置为AnnotationBeanConfigurerAspect之前,已执行TestPostConstruct对象的@PostConstruct方法。如果设置为调试的记录器将以下消息打印到控制台:“尚未在...上设置BeanFactory:确保此配置器在Spring容器中运行。无法配置类型[...]的Bean。继续进行操作,无需注入。 ”
是否有任何解决方法的问题仍对我开放...
我找到了一种解决方法。要在执行@PostConstruct之前初始化AnnotationBeanConfigurerAspect方面,可以使用此类@PostConstruct方法将以下注释添加到类中:
@DependsOn("org.springframework.context.config.internalBeanConfigurerAspect")
希望这些信息对某人有用。