Results 1 to 4 of 4

Thread: Put multiple bean instances in a collection

Hybrid View

  1. #1

    Default 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:

    Code:
        public List<Employee> empList = new ArrayList<Employee>();
    	
    	public Employee getEmployee() {
    		ApplicationContext empContext = new ClassPathXmlApplicationContext(
    				"employee-module.xml");
    		Employee emp = (Employee) empContext.getBean("empBean");
    		empList.add(emp);
    		return emp;
    	}

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,625

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3

    Default

    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. #4
    Join Date
    Dec 2009
    Location
    India
    Posts
    108

    Default

    @extremejava,

    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.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •