I have an object created as follows:
serviceValidatorObject = ServiceFactor开发者_JS百科y.getInstance().getServiceValidator()
The object is created from a call to static method, getInstance()
, then an instance method, getServiceValidator()
.
I want to use Spring injection to configure this instead.
The trouble is the ServiceFactory is legacy code that I cannot change.
I know Spring supports injection through a factory class static or instance method, but is there anyway I can configure the object creation above in Spring?
<bean id="exampleBean"
factory-bean="myFactoryBean"
factory-method="createInstance"/>
In your case, exampleBean is your serviceValidatorObject
, factory-bean is serviceFactory
, and the factory-method is getServiceValidator
. You might need this, too:
<bean id="serviceFactory"
factory-method="getInstance"/>
You could use this bean definition:
<bean id="serviceValidatorObject" factory-bean="serviceFactory" factory-method="getServiceValidator"/>
<bean id="serviceFactory" class="<package>.ServiceFactory" />
You should be able to achieve this using:
<bean id="myCreatedObjectBean" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass">
<value>com.mycompany.MyFactoryClass</value>
</property>
<property name="targetMethod">
<value>myFactoryMethod</value>
</property>
</bean>
Then you can use either @Resource or @Autowired + @Qualifier to inject into your object directly.
For this example, your applicationContext.xml should contain:
<!-- this allows Spring to create an instance of your Factory -->
<bean id="serviceFactoryBean" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass">
<value>yourpackage.ServiceFactory</value>
</property>
<property name="targetMethod">
<value>getInstance</value>
</property>
</bean>
<!-- this allows Spring to use the factory instance to create the instance of ServiceValidator -->
<bean id="serviceValidatorBean" factory-bean="serviceFactoryBean" factory-method="getServiceValidator"/>
And then you could inject into your code via:
@Resource(name = "serviceValidatorBean")
ServiceValidator serviceValidator;
精彩评论