Spring - Set properties to beans imported from another context file

Suppose you have imported some context files in your spring text file that you cannot modify.

Is there a way to import beans properties? I do not want to copy and paste the bean definition from the imported context files and modify it, because this will create the wrong dependency between my code and the external library.

I just need to change one property of an existing bean.

In theory, it should be possible that I can do this using a special class that gets a bean for updating as a dependency and changing its properties in the init method.

I am wondering if spring has standard syntax.

For example, in library-context.xml, the following bean definition exists:

<bean id="the.message" class="com.someco.SomeClass"> <property name="message" value="default message" /> </bean> 

I import this as an external dependency, and therefore I have no way to change this definition.

Of course, I can copy and paste this definition into my context and override it. This would be normal with a bean, as in the example, which is very simple. The problem is that dependencies are often much more complex, and they can change in another version of the library.

I want to set the bean property "the.message", ignoring all other details.

I am thinking of using something like:

 <bean id="myproxy" class="com.myapp.Proxy" init-method="copyProperties"> <property name="proxied" value="the.message" /> <property name="message" value="my message" /> </bean> 

This "proxy" is used only to set the "the.message" properties.

+5
source share
2 answers

To do what you want to do, SomeClass must have an installer. You just enter a bean, as usual, and use this setter. It would be easier to use annotations, but executable with XML.

However, make sure you understand that this will lead to a change in the value of the bean worldwide. If something depends on the initial value, it will no longer exist.

0
source

I believe this can be done using org.springframework.beans.factory.config.MethodInvokingFactoryBean in your import context file.

Using the imported definition from your example:

 <bean id="the.message" class="com.someco.SomeClass"> 

Message

can be set in the import context file as follows:

 <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="the.message" /> <property name="targetMethod" value="setMessage" /> <property name="arguments"> <list> <value type="java.lang.String">This message was set in importing context file</value> </list> </property> </bean> 
0
source

Source: https://habr.com/ru/post/1205344/


All Articles