首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Configurable不适用于@PostConstruct方法中初始化的对象

@Configurable不适用于@PostConstruct方法中初始化的对象
EN

Stack Overflow用户
提问于 2014-12-01 14:24:18
回答 2查看 1.7K关注 0票数 3

我通过编译时编织使用Spring和AspectJ,对非容器管理的对象使用@Configurable注释。

下面是一个@Configurable注释对象示例:

代码语言:javascript
复制
@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;
    }
}

组件,将其插入到此对象中:

代码语言:javascript
复制
@Component
public class TestComponent {}

当我在创建上下文之后创建TestConfigurable时,TestComponent可以很好地注入到那里,但是当我通过@PostConstruct注释的方法这样做时,自动装配就不会发生了。

组件具有@PostConstruct:

代码语言:javascript
复制
@Component
public class TestPostConstruct {

    @PostConstruct
    public void initialize() {
        TestConfigurable configurable = new TestConfigurable();
        System.out.println("In post construct: " + configurable.getComponent());
    }
}

我正在执行的应用程序:

代码语言:javascript
复制
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());
    }
}

下面是应用程序产生的输出:

代码语言:javascript
复制
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,不需要注入。“

如果有什么解决办法的话我还没解决.

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-02 08:21:08

我找到了一个解决办法。要在执行@PostConstruct之前初始化AnnotationBeanConfigurerAspect方面,可以使用以下@PostConstruct方法向类添加以下注释:

代码语言:javascript
复制
@DependsOn("org.springframework.context.config.internalBeanConfigurerAspect")

希望这些信息对某些人有帮助。

票数 5
EN

Stack Overflow用户

发布于 2021-09-24 18:05:18

我想,你忘了添加@EnableSpringConfigured。您必须使用此注释。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27230446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档