Spring 弹簧塞特法
我是否需要为实例变量使用setter方法将值注入对象 应用程序: 包com.processSpring 弹簧塞特法,spring,Spring,我是否需要为实例变量使用setter方法将值注入对象 应用程序: 包com.process import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[]args){ App
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[]args){
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");
Person sh = (Person) context.getBean("Person");
sh.displayname();
}
}
人:
package com.process;
public class Person {
String name;
public void displayname(){
System.out.println(name);
}
}
<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="Person" class="com.process.Person">
<property name="name" value="Bob" />
</bean>
</beans>
它仅适用于setter方法
问题:
我是否需要为每个实例变量使用setter方法
我是否需要为每个实例变量使用setter方法
您需要一个setter方法来设置
元素中声明的
您可以有一个与字段无关的setter。比如说
public class Person {
public void setFunky(String value){
System.out.println("random piece of code: " + value);
}
}
及
Spring认为它试图设置由
setFunky()方法表示的字段,以便执行它。您不需要实际访问/更改字段。要插入简单属性(如原语和字符串)的值,可以使用基于构造函数的依赖项注入或基于setter的依赖项注入
基于构造函数的依赖项注入:
public class Person {
String name;
public Person(String name){
this.name = name;
}
}
<bean id="Person" class="com.process.Person">
<constructor-arg type="java.lang.String" value="Bob" />
</bean>
public class Person {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<bean id="Person" class="com.process.Person">
<property name="name" value="Bob" />
</bean>
公共类人物{
字符串名;
公众人物(字符串名称){
this.name=名称;
}
}
基于Setter的依赖项注入:
public class Person {
String name;
public Person(String name){
this.name = name;
}
}
<bean id="Person" class="com.process.Person">
<constructor-arg type="java.lang.String" value="Bob" />
</bean>
public class Person {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<bean id="Person" class="com.process.Person">
<property name="name" value="Bob" />
</bean>
公共类人物{
字符串名;
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
}
但是您不能使用@Autowired
插入简单的属性,例如原语、字符串
。以下声明摘自:
属性和构造函数参数设置中的显式依赖项始终覆盖自动关联。不能自动关联所谓的简单属性,如原语、字符串和类(以及此类简单属性的数组)。这一限制是故意造成的
是的,spring将仅通过setter为属性设置值。