rayman
rayman

Reputation: 21596

Create Beans in Spring dynamiclly

I am using Spring3.1

My application will have kind of bean-manager.

That manager will be able to retrieve request and on each request I need to create new instance of bean dynamically which will be initiate with it's own unique params.

The params will be retrieved via the request method.

This bean must be alive and work asynchronously. (For example it will listen to jms calls, execute methods by demand and so on..)

Moreover I want to have the option to destroy beans also.

Those bean could be resemble as sessions so when the user log off i will destroy those beans.

I understand that I have to create some kind of bean-list or beans pool and manage it with some kind of manager.

How can I create those beans dynamically and have them remain them alive until I destroy them?

Any idea how could I implement such thing?

Upvotes: 2

Views: 4829

Answers (2)

Imran
Imran

Reputation: 5652

I've also found many trouble in creating a bean dynamically at run-time and used it anywhere in application..

Here is complete code

static ApplicationContext appContext = new ClassPathXmlApplicationContext(
            new String[] { "Spring-Question.xml" });
    static StaticApplicationContext innerContext = new StaticApplicationContext(appContext);

Create the bean and set the values e.g.

innerContext.registerSingleton("beanName", Test.class);
        Test test = innerContext.getBean(Test.class);
        test.setA(3);
        test.setB(4);

Then Re-Use the bean anywhere in application....

Test test = innerContext.getBean(Test.class);
        System.out.println(test.setB(4));

Upvotes: 0

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

Well in this sense, the easiest way would be to create a StaticApplicationContext setting its parent context as the common context (the one holding the beans you want to share over all). This you could reach by doing something like:

StaticApplicationContext innerContext = new StaticApplicationContext(parentContext);

after this, you probably want to declare the bean you want to instantiate over Spring in order to attach all the AOP stuff, Autowiring and other functionalities, therefore you will need to do something like:

innerContext.registerSingleton("beanName", beanClass);

After registering you could instantiate the bean like:

innerContext.getBean(beanClass);

Of course there is the implementation of scope Session for spring and therefore I advise you to check the WebApplicationContext documentation, method loadParentContext that you basically pass the ServletContext as paramenter.

Upvotes: 3

Related Questions