15

Define a public bean variable in the spring without using a setter

 4 years ago
source link: https://www.codesd.com/item/define-a-public-bean-variable-in-the-spring-without-using-a-setter.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Define a public bean variable in the spring without using a setter

advertisements

I read on a few websites that with Spring its possible to do setter based Dependency Injection without having to create a setter for the injected variable it. Would nicely tidy up the code. I read this on another site and also here on stackoverflow.

I've tried it but in my case it does not work. I'm using 3.2.0.RELEASE. I'm getting the following error.

 Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'DI_without_setter' defined in class path resource [SpringBeans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'url' of bean class [net.comsys.springpropstest.DiWithoutSetter]: Bean property 'url' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

my Java test code

package net.xxx.springpropstest;

public class DiWithoutSetter {
private String url;
}

I've just added it to my main code. Not displayed here. I don't even use DiWithoutSetter in the main code.

SpringBeans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="DI_without_setter" class="net.xxx.springpropstest.DiWithoutSetter">
    <property name="url" value="jan" />
</bean>

If someone could shed some light on his issue that would be appreciated. Is it possible to set the value of a (public) variable in a Spring bean without using a setter method?


You can't do that (you need a setter), and that tutorial appears to be wrong (note in the example source zip, the classes have getters and setters).

Either add a setter or @Inject the field implicitly using autowiring.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK