Issue
I'd like to know what are the differences between the two examples below. One is using @PostConstruct init method to ensure autowired bean is initialized, and the other one is using constructor with @Autowired to ensure any needed beans are initialized.
- If there is any functional differences
- If one is better than the other, why? (Maybe initialization speed, less call stack, less memory usage, etc.)
Thanks in advance :)
@Component
public class MyBean {
@Autowired
public MyBean(SomeOtherBean someOtherBean) {
...
}
...
}
@Component
public class MyBean {
@Autowired
private SomeOtherBean someOtherBean;
@PostConstruct
public void init() {
...
}
...
}
Solution
in the first case, if I'm going to use MyBean.class without in a none Spring framework project I'll need to pass SomeOtherBean so I know the object is created correctly. but in the second case, I would have done new MyBean() and then after I'll get NullPointerException when using it because the object depends on SomeOtherBean. so the first one is much cleaner.
Answered By - stacker
Answer Checked By - Cary Denson (JavaFixing Admin)