2
votes

I have a class that wants to use some @Autowired service classes as fields, but that class itself is not a @service or a @Component, because it needs a non-default constructor to use it correctly.

Is there an annotation to declare that "please scan this class for @Autowiring but it is not a spring bean itself"? This seems like a genuine use case to me (client wants to autowire and use some beans, but itself not a spring bean)?

2

2 Answers

0
votes

You can try something like

<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;
    }
}

For the class which has to be autowired. See this for more information.

0
votes

You need to manually inject the bean and use context:annotation config . If you have a class as follows

public class ABD{

@Autowired
public Bean2 b2;    

}

and If you inject ABD to some other bean thru constructor injection , @Autowired will apply else spring will not be able to instatiate your bean as it does not have a no argument constructor .

On the other hand if your Object is not a bean , see the discussion on this at How to autowire a bean inside a class that is not a configured bean? . The code goes something like this

        context.getAutowireCapableBeanFactory().autowireBean(this);

To get the context in a non Spring bean , you could probably use the ContextSingletonBeanFactoryLocator . But it is a lot easier if you cold make this a spring bean using constructor injection .