【问题标题】:Spring client not a spring bean, but wants autowired bean fieldsSpring 客户端不是 Spring bean,但需要自动装配的 bean 字段
【发布时间】:2012-01-05 06:48:00
【问题描述】:
我有一个类想要使用一些@Autowired 服务类作为字段,但该类本身不是@service 或@Component,因为它需要一个非默认构造函数才能正确使用它。
是否有注释声明“请扫描此类以查找@Autowiring 但它本身不是spring bean”?这对我来说似乎是一个真正的用例(客户想要自动装配并使用一些 bean,但它本身不是 Spring bean)?
【问题讨论】:
标签:
spring
dependency-injection
【解决方案1】:
你可以试试
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg type="int"><value>1</value></constructor-arg>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public ExampleBean(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
this.beanOne = anotherBean;
this.beanTwo = yetAnotherBean;
this.i = i;
}
}
对于必须自动装配的类。请参阅this 了解更多信息。
【解决方案2】:
您需要手动注入 bean 并使用 context:annotation config 。如果你有一个类如下
public class ABD{
@Autowired
public Bean2 b2;
}
如果您通过构造函数注入将 ABD 注入其他 bean,@Autowired 将应用,否则 spring 将无法实例化您的 bean,因为它没有无参数构造函数。
另一方面,如果您的 Object 不是 bean ,请参阅How to autowire a bean inside a class that is not a configured bean? 上的讨论。代码是这样的
context.getAutowireCapableBeanFactory().autowireBean(this);
要在非 Spring bean 中获取上下文,您可以使用 ContextSingletonBeanFactoryLocator 。但是,如果您使用构造函数注入将其作为 Spring bean 进行冷处理,则会容易得多。