How to pass parameters dynamically to Spring beans How to pass parameters dynamically to Spring beans spring spring

How to pass parameters dynamically to Spring beans


If i get you right, then the correct answer is to use getBean(String beanName, Object... args) method, which will pass arguments to the bean. I can show you, how it is done for Java based configuration, but you'll have to find out how it is done for an XML based configuration.

@Configurationpublic class ApplicationConfiguration {        @Bean  @Scope("prototype")  // As we want to create several beans with different args, right?  String hello(String name) {    return "Hello, " + name;  }}// and later in your applicationAnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);String helloCat = (String) context.getBean("hello", "Cat");String helloDog = (String) context.getBean("hello", "Dog");

Is this what are you looking for?


UPDATE

This answer gets too much upvotes and nobody looks at my comment. Even though it's a solution to the problem, it is considered as a Spring anti-pattern and you shouldn't use it! There are several different ways to do things right using factory, lookup-method, etc.

Please use the following SO post as a point of reference:


Please have a look at Constructor injection.

Also, Have a look at IntializingBean and BeanPostProcessor for other life cycle interception of a springbean.


I think the answers proposed above to use constructor injection/setter injection doesn't work perfectly for the use case you are looking for.Spring more or less takes static argument values for constructors/setters. I don't see a way to dynamically pass values to get a Bean from Spring Container.However, if you want to get instances of User_Imple dynamically, I would recommend using a factory class User_Imple_Factory

     public class User_Imple_factory {        private static ApplicationContext context =new ClassPathXmlApplicationContext("/bean.xml");        public User_Imple createUserImple(int id) {            User user = context.getBean("User");            return new User_Imple(id, user);        }    }