我在一些网站上读到,使用 Spring 可以进行基于 setter 的依赖注入(inject),而不必为注入(inject)的变量创建 setter。很好地整理了代码。我读过这个on another网站以及 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 中设置(公共(public))变量的值?
最佳答案
您不能这样做(您需要一个 setter),并且该教程似乎是错误的(请注意,在示例源 zip 中,类具有 getter 和 setter)。
使用 Autowiring 隐式添加 setter 或 @Inject
字段。
关于java - 在spring中设置bean的公共(public)变量而不使用setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14384376/