2012-01-05 105 views
1

我有一个类想要使用一些@Autowired服务类作为字段,但该类本身不是@service或@Component,因为它需要一个非默认构造函数正确使用它。Spring客户端不是spring bean,但想要自动布线的bean字段

是否有一个注释来声明“请扫描此类的@Autowiring,但它不是一个spring bean本身”?这对我来说似乎是一个真正的用例(客户想要自动装配并使用一些bean,但它本身不是spring bean)?

回答

0

您需要手动注入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,它会容易得多。

0

你可以尝试像

<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