Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring to inject an object in a setter that doesnt follow the Java bean specification?

I am trying to use Spring and wx-xmlrpc together. The problem is that XmlRpcClient has a setConfig() method that doesnt follow the Java Bean spec : the setter and the getter dont use the same Class. So Spring complaints when I have the following context.xml :

<bean id="xmlRpcClient" class="org.apache.xmlrpc.client.XmlRpcClient">
    <property name="config">
        <bean class="org.apache.xmlrpc.client.XmlRpcClientConfigImpl">
            <property name="serverURL" value="http://example.net" />
        </bean>
    </property>
</bean>

It says : Bean property 'config' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Is there a way to override that ? I know I could write a specific factory for this bean, but it seems to me that it is not the last time I find this kind of problem. I work a lot with legacy code of dubious quality ... Being able to use Spring XML configuration with it would be a great help !

like image 485
Guillaume Avatar asked Jul 31 '09 21:07

Guillaume


People also ask

Which injection is used for non mandatory dependencies?

Setter based Injection - It can be used by calling setter methods on your beans. It should be used for optional dependencies.

Which dependency injection is not supported by Java Spring directly?

There are three types of injection: Constructor, Setter and Interface. Spring doesn't support the latest directly(as I have observed people saying).

Can we use @bean without @configuration?

@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.

Why is field injection not recommended in Spring?

The reasons why field injection is frowned upon are as follows: You cannot create immutable objects, as you can with constructor injection. Your classes have tight coupling with your DI container and cannot be used outside of it. Your classes cannot be instantiated (for example in unit tests) without reflection.


1 Answers

Write a FactoryBean for that class and have it call the correct setter.

like image 165
mP. Avatar answered Nov 21 '22 18:11

mP.