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

 爱啊诗的孩子 发布于 2022-12-08 18:54

我通过编译时编织将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。继续进行操作,无需注入。 ”

是否有任何解决方法的问题仍对我开放...

1 个回答
  • 我找到了一种解决方法。要在执行@PostConstruct之前初始化AnnotationBeanConfigurerAspect方面,可以使用此类@PostConstruct方法将以下注释添加到类中:

    @DependsOn("org.springframework.context.config.internalBeanConfigurerAspect")
    

    希望这些信息对某人有用。

    2022-12-11 02:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有