How to create a object that need dynamic parameter

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.

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 Sprign to initialize objects created with new. Though it requires some extra configuration of runtime environment.


Need Your Help

CSS Media Queries, Opera and Firefox trouble

css firefox css3 opera media-queries

I'm using the Ubuntu font for my website and Opera doesn't render the page when I do:

Only allow special characters in Textbox when pressing keys on keyboard

.net wpf text

I need a textbox where the user only can work with uppercase characters. Also some special characters like - _ and &lt;.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.