Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a object that need dynamic parameter

Tags:

java

spring

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.

like image 708
Neo Avatar asked Dec 27 '22 18:12

Neo


1 Answers

  • The most straightforward way to do it is to use ApplicationContext.getBean(String name, Object... args) - it can create a prototype-scoped bean passing the given arguments to its constructor. Obviosly it's not a good idea to use ApplicationContext directly in any bean that uses A.

  • A more elegant approach is to hide the creation of A behind 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-public initialization method to pass that parameters (instead of passing parameters through using constructor).

  • Yet another apporach is to use @Configurable and load-time weaving that allows Spring to initialize objects created with new. Though it requires some extra configuration of runtime environment.

like image 178
axtavt Avatar answered Dec 31 '22 13:12

axtavt