How to pass parameters dynamically to Spring beans

后端 未结 5 2162
盖世英雄少女心
盖世英雄少女心 2020-12-28 14:31

I am new to Spring.

This is the code for bean registration:

 


        
5条回答
  •  孤独总比滥情好
    2020-12-28 15:11

    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);
            }
        }
    
    

提交回复
热议问题