3

我通过编译时编织将 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 不在这里进行自动装配?

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

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

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

4

2 回答 2

5

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

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

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

于 2014-12-02T08:21:08.353 回答
0

我猜,您忘记添加@EnableSpringConfigured。您必须使用此注释。

于 2021-09-24T18:05:18.747 回答