如何动态地将参数传递给Spring bean

我是Spring的新手。

这是bean注册的代码:

    

这是我的bean类:

 public class User_Imple implements Master_interface { private int id; private User user; // here user is another class public User_Imple() { super(); } public User_Imple(int id, User user) { super(); this.id = id; this.user = user; } // some extra functions here.... } 

这是我执行操作的主要方法:

 public static void main(String arg[]) { ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml"); Master_interface master = (Master_interface)context.getBean("user"); // here is my some operations.. int id = ... User user = ... // here is where i want to get a Spring bean User_Imple userImpl; //want Spring-managed bean created with above params } 

现在我想用参数调用这个构造函数,这些参数是在我的main方法中动态生成的。 这就是我想要动态传递的意思 – 不是静态传递,就像在我的bean.config文件中声明的bean.config

请看一下Constructor注入 。

另外,看一下IntializingBean和BeanPostProcessor ,以获取springbean的其他生命周期拦截。

如果我说得对,那么正确的答案是使用#getBean(String beanName,Object … args)将参数传递给bean。 我可以告诉你,它是如何为基于java的配置完成的,但你必须找到它是如何为基于xml的配置完成的。

 @Configuration public 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 application AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class); String helloCat = (String) context.getBean("hello", "Cat"); String helloDog = (String) context.getBean("hello", "Dog"); 

这是你在寻找什么?

UPD。 这个答案得到了太多的赞成,没有人看我的评论。 即使它是问题的解决方案,它也被认为是弹簧反模式,你不应该使用它! 有几种不同的方法可以使用工厂,查找方法等来做正确的事情。

请使用以下SOpost作为参考: 在运行时创建bean

构造函数注入可以帮助您。 在这种情况下,您可能需要生成一个包含ID和user作为其属性的POJO,并将POJO传递给构造函数。 在配置文件中的构造函数注入中,您可以使用pojo作为引用来引用此构造函数。 因此,您将处理ID和用户中数据的动态值。

希望这可以帮助 !!

我认为上面提出的使用构造函数注入/设置器注入的答案对于您正在寻找的用例并不完美。 Spring或多或少采用构造函数/ setter的静态参数值。 我没有看到动态传递值以从Spring容器中获取Bean的方法。 但是,如果您想动态获取User_Imple的实例,我建议使用工厂类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); } }
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); } } 

也许让User_Imple成为普通的Pojo(而不是Spring bean)会解决你的问题?

   

Java的:

 public static void main(String arg[]) { ApplicationContext context =new ClassPathXmlApplicationContext("/bean.xml"); User user = context.getBean(User.class); int id = // dynamic id Master_interface master = new User_Imple(id, user); }