Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a preConstruction alike for a spring stereotype annotation?

Tags:

java

spring

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 :

@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
public class MyDomainRepository {

  @Autowired private MyContext context;

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

}
like image 443
Albert Gan Avatar asked Oct 14 '25 18:10

Albert Gan


1 Answers

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:

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

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

like image 108
axtavt Avatar answered Oct 17 '25 08:10

axtavt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!