I always have a question from the 1st day when I used spring. If a class has a constructor that needs two parameters, but these 2 parameters are not fixed, they are generated according to input request, every time they are different, but I need spring container to manage the class’s instance, how to achieve this in spring?
For example
Class A{
A(int x,int y){//omit}
}
but x, and y are not fixed,we need to calculate x and y by our program, then we can create instance for A, in ordinary java code,like below
int x=calculate(request);
int y=calculate(request);
A a=new A(x,y);
But how to make spring manages the class A’s instance creation?
Additional information: Why I need Class A is managed by spring, because A depends on some other classes which are managed by spring.
The most straightforward way to do it is to use
ApplicationContext.getBean(String name, Object... args)– it can create aprototype-scoped bean passing the given arguments to its constructor. Obviosly it’s not a good idea to useApplicationContextdirectly in any bean that usesA.A more elegant approach is to hide the creation of
Abehind a factory. That factory can use the previous approach internally, or it can obtain an instance of a bean in a regular way (Provider<A>, etc) and then call a non-publicinitialization method to pass that parameters (instead of passing parameters through using constructor).Yet another apporach is to use
@Configurableand load-time weaving that allows Spring to initialize objects created withnew. Though it requires some extra configuration of runtime environment.