In Spring there is a feature autowiring, that will auto resolve and inject object dependency. With the help of autowriring, we does not need to explicitly inject the dependency and reduce the amount of code we need to write. However, simplicity doesn’t come free, once a class is annotated to be Spring bean, Spring will take control of that particular class’s object lifecycle (from creation to destroy) and we will lose some control towards it.
So, this problem bug me for a while as I want to have full control towards my object but at the same time enjoy the autowring feature. In Spring, there is a class AutowireCapableBeanFactory that could help us to achieve this.
This is the class we want to have full control toward it.
1
2
3
4
5
6
7
8
9
10
public class MyObject {
@Autowired
private ServiceA serviceA;
@Autowired
private RepositoryB repositoryB;
...
}
We can simply autowire the dependency as below:
1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class MyObject {
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
public MyObject intiMyObject() {
MyObject myObject = new MyObject();
autowireCapableBeanFactory.autowireBean(myObject);
return myObject;
}
}