2

我在一些网站上读到,使用 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 中设置(公共)变量的值?

4

2 回答 2

1

您不能这样做(您需要一个 setter),并且该教程似乎是错误的(请注意在示例源 zip 中,这些类有 getter 和 setter)。

@Inject使用自动装配隐式添加 setter 或字段。

于 2013-01-17T17:23:45.920 回答
1

You would need to annotate the field with @Autowired and enable component scanning for this injection to work without a setter method.

于 2013-01-17T17:31:12.840 回答