Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Prototype-Bean Provider without @Autowired

Tags:

java

spring

I have a prototype Bean which is instantiated by singleton bean with a Provider:

@Component
@Scope("prototype")
class MyPrototype {}

@Component
class MySingleton {
    @Autowired
    javax.inject.Provider<MyPrototype> prototypeFactory;
}

This works fine, but our company rules state that @Autowired is not allowed; the common pattern is @Resource(SingletonBeanClass.BEAN_ID).

Is it possible to annotate the Provider this way so the Spring lookup can create it?

I'm aware I can add a factory method with @Lookup, or a singleton factory bean, but I prefer the Provider.

EDIT: I didn't get it to work this way and in the end had to edit spring.xml; see below for details.

like image 555
daniu Avatar asked Nov 08 '22 15:11

daniu


1 Answers

As you have an XML configuration file, you can configure it via XML in the following way:

<bean id="myPrototype" class="some.package.MyPrototype" scope="prototype" />

<bean id="mySingleton" class="some.package.MySingleton">
    <lookup-method name="getPrototypeFactory" bean="myPrototype "/>
</bean>

In this way, you have to access to the myPrototype with the getPrototypeFactory() and not directly to the property. You can even remove the annotations on those 2 classes.

For any extra details, you can look at the following blog post Injecting a prototype bean into a singleton bean

like image 143
araknoid Avatar answered Nov 15 '22 11:11

araknoid