If i have :
@Component
class Foo {
@Autowired
private Bar b; //where b is @Service
public Foo(){
//if i need to use b here, what do i need to do?
b.something(); // <-- b is null so it'll crash here
}
public void setB(Bar b){
this.b = b;
}
}
From reading Spring docs i understand that setter-based injection method is recommended over constructor based injection but in above example i need to be using the injected spring class inside the constructor of current class so for that it HAS to be constructor based injection correct?
If so is this what it’s going to look like?
@Component
class Foo {
private Bar b; //where b is @Service
@Autowired
public Foo(Bar b){
b.something(); // b won't be null now !
}
}
You can create a method annotated with @PostConstruct, as already mentioned:
http://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/
This requires an additional dependency and some configuration.
The usual way to do what you want is to make your bean implement the Spring interface
InitializingBean.The
afterPropertiesSet()method you can implement will be triggered by Spring, after all its dependencies are injected.You’d better use the annotations, once configured it is simpler, easier to read, and compatible with Java EE.