【问题标题】:@Configurable doesn't work for objects initialized in @PostConstruct methods@Configurable 不适用于在 @PostConstruct 方法中初始化的对象
【发布时间】:2015-01-29 13:54:42
【问题描述】:

我正在通过编译时编织将 Spring 与 AspectJ 一起使用,以对非容器管理的对象使用 @Configurable spring 注释。

这是一个示例@Configurable-annotated 对象:

@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 不在这里进行自动装配?..

如果它们有助于解决问题,可以发布其他配置文件(context 和 pom.xml)。

更新 1: 看起来我找到了问题的原因。使用 @Configurable 注解的对象由实现 BeanFactoryAware 的 AnnotationBeanConfigurerAspect 初始化。这个方面使用 BeanFactory 来初始化 bean。看起来 TestPostConstruct 对象的 @PostConstruct 方法是在 BeanFactory 设置为 AnnotationBeanConfigurerAspect 之前执行的。如果记录器设置为调试,则将以下消息打印到控制台:“BeanFactory 尚未设置在 ...:确保此配置器在 Spring 容器中运行。无法配置类型 [...] 的 bean。继续无需注射。”

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

【问题讨论】:

  • 不是真正解决这个问题的方法,而是使用@Configurable,你可以简单地在你的组件中注入一个工厂。

标签: spring aspectj configurable postconstruct compile-time-weaving


【解决方案1】:

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

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

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

【讨论】:

  • 如果您认为这是正确的答案,您可以接受自己的答案以结束问题。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    相关资源
    最近更新 更多