java spring 构造型注释是否有类似的预构造?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11716301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:07:40  来源:igfitidea点击:

Is there a preConstruction alike for a spring stereotype annotation?

javaspring

提问by bertie

I could make use of preConstruction=true for my domain class so that i can make use of autowired fields in the constructor such as this :

我可以将 preConstruction=true 用于我的域类,以便我可以在构造函数中使用自动装配的字段,例如:

@Configurable(preConstruction=true)
public class MyDomain {

  @Autowired private MyContext context;

  public MyDomain() {
    context.doSomething(this); // access the autowired context in the constructor
  }

}

But then, what is the equivalence for preConstruction when i would like to access autowired fields in a class with the normal stereotype annotation such as @Repository or @Service aside from constructor injection (Currently using spring 3.x here ..) ?

但是,除了构造函数注入之外,当我想使用普通构造型注释(例如@Repository 或 @Service)访问类中的自动装配字段时,preConstruction 的等效性是什么(目前在此处使用 spring 3.x ..)?

@Repository
public class MyDomainRepository {

  @Autowired private MyContext context;

  public MyDomain() {
    // cannot access the autowired context in the constructor
    context.doSomething(this); 
  }

}

采纳答案by axtavt

I don't think something like this is available for regular Spring beans, but the usual way to solve this problem is to use @PostConstruct-annotated method instead of constructor:

我不认为这样的东西可用于常规 Spring bean,但解决这个问题的常用方法是使用@PostConstruct-annotated 方法而不是构造函数:

@PostConstruct
public void init() {
    context.doSomething(this);    
} 

This method will be called by Spring after all dependencies are injected.

注入所有依赖项后,Spring 将调用此方法。