@Configurable(preConstruction = false)
public class Mock implements IMock
{
@Autowired
private Foo foo;
public Mock()
{
System.out.println("i need foo in the constructor but it is not autowired at this point " + foo);
}
@PostConstruct
public void start()
{
System.out.println("starting");
}
}
当我设置 Spring Aspectj 加载时编织并通过 new
关键字创建一个实例时,如下所示(如下)。事实证明,我无法访问构造函数中的依赖项。一切都如预期的那样好。执行顺序是 constructor->autowire->postconstruct
。
public class Main
{
public static void main(String[] args)
{
URL url = Main.class.getResource("applicationContext.xml");
FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(url.getPath());
Mock mock = new Mock();
}
}
所以我设置了@Configurable(preConstruction = true)
。现在我可以访问构造函数中的依赖项。但问题是执行顺序: autowire->postconstruct->construct
。为什么后构造先于构造?这不是我所期望的。
我是不是误会了什么? @PostConstruct 的语义是什么?是“构造函数后”还是“依赖注入(inject)后”?我查看了@PostConstruct 的javadoc。它没有提及构造函数。
编辑:顺便说一句,这是我使用的库版本:
spring-aspects 4.1.6.RELEASE
Spring 仪器4.1.6.RELEASE
最佳答案
@PostConstruct
在 Spring 中由 CommonAnnotationBeanPostProcessor
处理,并与为给定 bean 工厂配置并适用于该 bean 的所有 bean 配置后处理器一起运行有问题(按照它们配置运行的顺序)。 @Configurable
注解只是标记非 Spring 管理的 bean 符合 Spring Autowiring 和 bean 后处理的条件,并且它是通过 AnnotationBeanConfigurerAspect
完成的。 preConstruction=true
将表明此配置应在相关对象的构造函数运行之前发生。这意味着,如果 preConstruction=true
,则在运行相关对象的构造函数时,Spring 将完成该对象的配置。
TL;DR - 是的,这是您的情况应该发生的预期顺序。
关于java - 关于Springaspectj加载时织入执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48574795/