我有一個類想要使用一些@Autowired服務類作爲字段,但該類本身不是@service或@Component,因爲它需要一個非默認構造函數正確使用它。Spring客戶端不是spring bean,但想要自動佈線的bean字段
是否有一個註釋來聲明「請掃描此類的@Autowiring,但它不是一個spring bean本身」?這對我來說似乎是一個真正的用例(客戶想要自動裝配並使用一些bean,但它本身不是spring bean)?
我有一個類想要使用一些@Autowired服務類作爲字段,但該類本身不是@service或@Component,因爲它需要一個非默認構造函數正確使用它。Spring客戶端不是spring bean,但想要自動佈線的bean字段
是否有一個註釋來聲明「請掃描此類的@Autowiring,但它不是一個spring bean本身」?這對我來說似乎是一個真正的用例(客戶想要自動裝配並使用一些bean,但它本身不是spring bean)?
您需要手動注入bean並使用context:annotation config。如果你有一個類如下
public class ABD{
@Autowired
public Bean2 b2;
}
,如果你注入ABD一些其他的bean直通構造函數注入,@Autowired將適用於其他的彈簧將不能因爲它不給你instatiate豆有一個沒有參數的構造函數。
另一方面,如果您的對象不是一個bean,請參閱How to autowire a bean inside a class that is not a configured bean?上的討論。該代碼是這樣
context.getAutowireCapableBeanFactory().autowireBean(this);
收穫的人在非的Spring bean的背景下,你很可能使用ContextSingletonBeanFactoryLocator的。但如果你使用構造函數注入將它變成一個spring bean,它會容易得多。
你可以嘗試像
<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。