Spring Prototype <Bean Provider without @Autowired
I have a Bean prototype that is instantiated by a singleton Bean with Provider
:
@Component
@Scope("prototype")
class MyPrototype {}
@Component
class MySingleton {
@Autowired
javax.inject.Provider<MyPrototype> prototypeFactory;
}
This works fine, but our company’s rules state that it’s @Autowired
not allowed; general template @Resource(SingletonBeanClass.BEAN_ID)
.
Is it possible to annotate Provider
in such a way that Spring search can create it?
I know that I can add a factory method with @Lookup
or a singleton factory bean, but I prefer Provider
.
EDIT: I didn’t manage to work like that and, in the end, had to edit it spring.xml
; see below for more details.
Since you have an XML configuration file, you can configure it using XML as follows:
<bean id="myPrototype" class="some.package.MyPrototype" scope="prototype" />
<bean id="mySingleton" class="some.package.MySingleton">
<lookup-method name="getPrototypeFactory" bean="myPrototype "/>
</bean>
, myPrototype getPrototypeFactory()
, . .
, - Google:
spring.xml
. @Lookup
, - bean, - bean.
@Component("proto1")
@Scope("prototype")
class MyPrototypeBean1 {
@Lookup(value="proto2")
protected MyPrototypeBean2 createBean2() { return null; }
}
@Component("proto2")
@Scope("prototype")
class MyPrototypeBean2 {
}
@Component("singleton")
class MySingleton {
@Lookup(value="proto1")
protected MyPrototypeBean1 createBean1() { return null; }
}
" @Lookup beans bean" "innerBean...".
, , beans, factory, ", .
, spring.xml
:
<bean name="proto2" class="my.package.PrototypeBean2" />
<bean name="proto1" class="my.package.PrototypeBean1" >
<lookup-method name="createBean2" bean="proto2" />
</bean>
<bean name="singleton" class="my.package.SingletonBean" >
<lookup-method name="createBean1" bean="proto1" />
</bean>
.
:
class SingletonUnitTest {
@Mock
MyPrototypeBean1 bean1;
@InjectMocks
DummySingleton sut;
@Before public void setBean1() {
sut.bean = bean1;
}
static class DummySingletonBean extends MySingeton {
MyPrototypeBean1 bean;
protected MyPrototypeBean1 createBean1() {
return bean;
}
}
}