Announcement Announcement Module
No announcement yet.
Put multiple bean instances in a collection Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Put multiple bean instances in a collection

    My requirement is put multiple instances of a bean (scope=prototype) into an ArrayList.
    Is there any automatic way to achieve it.
    Currently I have written a helper class to return the bean instance and also add this new instances to member ArrayList as shown below:

        public List<Employee> empList = new ArrayList<Employee>();
    	public Employee getEmployee() {
    		ApplicationContext empContext = new ClassPathXmlApplicationContext(
    		Employee emp = (Employee) empContext.getBean("empBean");
    		return emp;

  • #2
    I really hope that this isn't code you are seriously using in a production system... NEVER create an instance of the application context just for the sake of retrieving a bean. Unless you want to get memory problems, concurrency problems, tx problems... So in short never do this. Next to that you have code with side-effects (it isn't a simply getter it adds something to a list)...

    If you want to retrieve bean instances simply make the bean that needs this ApplicationContextAware or BeanFactoryAware that way you get access to the ApplicationContext/BeanFactory and can simply do a getBean on there.


    • #3
      My problem is not for bean instantiation but is about how to maintain an arraylist of all instances of Employee class.
      The code is just for demonstration purpose.


      • #4

        you're only stopping yourself here. just read a bit and think programmatically. Anyway, i don't know what you intend to do but learn to apply yourself a bit when using spring. Its lot more fun than you can imagine at this stage. Don't run around for these petty issues. I think this forum is not for learning spring.