简体   繁体   English

带参数的Spring原型bean?

[英]Spring prototype beans with parameters?

Is it possible to define a prototype bean , using XML config or annotation-based config such that I can get an instance of the bean with a custom parameter value? 是否可以使用XML配置或基于注释的配置来定义原型bean ,以便我可以使用自定义参数值获取bean的实例? My use case is a message queue handler that makes API calls with different parameter values that are supplied in the inbound message. 我的用例是一个消息队列处理程序,它使用入站消息中提供的不同参数值进行API调用。

In this case it seems I can do one of two things: 在这种情况下,似乎我可以做两件事之一:

  • Get an instance of my prototype-scope bean and then call setters to customize it to be specific to the inbound message. 获取我的原型范围bean的实例,然后调用setter将其自定义为特定于入站消息。
  • Construct a new instance of the bean class using a plain new MyPrototypeBean() and then call setters to customize the instance. 使用普通的new MyPrototypeBean()构造bean类的新实例,然后调用setter来自定义实例。

Perhaps a different way of wording my question is: What is the benefit of using a prototype-scope bean vs. using a simple Java constructor? 也许用另一种方式来解释我的问题:使用原型范围bean与使用简单的Java构造函数有什么好处?

To get a prototype bean from another bean while passing arguments to constructor you can use <lookup-method> (XML Configuration) or @Lookup (annotation-based configuration). 要在将参数传递给构造函数的同时从另一个bean获取原型bean,可以使用<lookup-method> (XML Configuration)或@Lookup (基于注释的配置)。

If you want to get the prototype instance from "unmanaged" code (not from a bean) or you don't want to use the lookup methods, you can achieve the same using org.springframework.beans.factory.BeanFactory.getBean(String beanName, Object...) . 如果你想从“非托管”代码(而不是bean)获取原型实例, 或者你不想使用查找方法,你可以使用org.springframework.beans.factory.BeanFactory.getBean(String beanName, Object...)org.springframework.beans.factory.BeanFactory.getBean(String beanName, Object...)

Answering your second question, difference between a prototype-scope bean and using a simple Java constructor is that the prototype-scope bean still have access to Spring container's features. 回答第二个问题,原型范围bean和使用简单Java构造函数之间的区别在于原型范围bean仍然可以访问Spring容器的功能。 This includes, but it's not limited to the following: it can have collaborators provided in XML configuration ( <property name="someCollaborator" ref="..."/> ) or with annotations ( @Resource , @Autowired , ...), t can implement Spring-aware interfaces (like ApplicationContextAware so that the prototype bean itself has access to the container). 这包括但不限于以下内容:它可以在XML配置中提供协作者( <property name="someCollaborator" ref="..."/> )或注释( @Resource ,@ @Autowired ,... ),t可以实现Spring感知接口(如ApplicationContextAware以便原型bean本身可以访问容器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM