java - 在spring中设置bean的公共(public)变量而不使用setter

标签 java spring

我在一些网站上读到,使用 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/

相关文章:

java - 如何创建 MockNdefMessages

java - 如何查找 CSRF token 是否有效

java - 我们可以在 Spring WS 中使用多个消息工厂吗?

java - Intent 不断使我的应用程序崩溃?

java - Spring 工具套件(以及所有 Spring 项目)中出现未知的 Spring 错误 我该如何解决?

Spring 社交/连接返回 404

java - Spring Data REST 事件不起作用

java - Spring & Hibernate 的连接池

java - JAVA 和 MYSQL 中的 WEEK_OF_YEAR 错误

java - Java 中数组的不常见语法