我在一些网站上读到,使用 Spring 可以进行基于 setter 的依赖注入,而无需为注入的变量创建 setter。会很好地整理代码。我在另一个网站上读到了这个,也在stackoverflow上读到了这个。
我已经尝试过了,但在我的情况下它不起作用。我正在使用 3.2.0.RELEASE。我收到以下错误。
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?
我的 Java 测试代码
包 net.xxx.springpropstest;
public class DiWithoutSetter {
private String url;
}
我刚刚将它添加到我的主代码中。此处不显示。我什至不在主代码中使用 DiWithoutSetter。
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>
如果有人能对他的问题有所了解,那将不胜感激。是否可以在不使用 setter 方法的情况下在 Spring bean 中设置(公共)变量的值?