我正在阅读有关Springs Dependency注入功能的教科书。这本书有一个我发现难以复制的例子。本书使用的配置类包含私有字段中的所需值。我只能通过将这些字段更改为公开来使应用程序正常工作。
我使用的配置类是
package com.annotation.testing;
import org.springframework.stereotype.Component;
@Component("injectSimpleConfig")
public class InjectSimpleConfig {
//these fields are private in the text book
public String name="MyName";
public int age=21;
}
我的申请
package com.annotation.testing;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service("injectSimpleSpel")
public class InjectSimpleSpel {
@Value("#{injectSimpleConfig.name}")
private String name;
@Value("#{injectSimpleConfig.age+1}")
private int age;
@Override
public String toString() {
return "Name: " + name +"\n"
+"Age: " + age;
}
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context-xml2.xml");
ctx.refresh();
InjectSimpleSpel om = (InjectSimpleSpel)ctx.getBean("injectSimpleSpel");
System.out.println(om);
ctx.close();
}
}
和xml文件(app-context-xml2.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.annotation.testing"/>
<bean id="injectSimpleConfig" class="com.annotation.testing.InjectSimpleConfig"/>
<bean id="injectSimpleSpel" class="com.annotation.testing.InjectSimpleSpel"/>
</beans>
我的问题是,我需要做哪些更改才能使应用程序与配置类中的私有字段一起使用?或者,这本书错了吗?应该将配置类中的字段公开以使应用程序正常工作吗?