spring用setter注入的方式
时间: 2023-09-03 19:15:50 浏览: 35
Spring使用setter方法来进行依赖注入,以下是步骤:
1. 创建一个Java类,该类的属性将被注入。
2. 为该类创建一个setter方法,用于设置属性的值。
3. 在Spring配置文件中,使用<bean>标签来定义该类的bean。
4. 在<bean>标签中使用<property>标签,设置属性的名称和值。
5. 在<property>标签中使用value属性指定要注入的值,或者使用ref属性指定要注入的另一个bean。
6. 在程序中使用ApplicationContext类来获取该类的bean,并调用其setter方法,将值注入属性中。
例如,以下是一个简单的示例:
```
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
```
在Spring配置文件中,定义Person类的bean:
```
<bean id="person" class="com.example.Person">
<property name="name" value="John Doe" />
<property name="age" value="30" />
</bean>
```
在程序中获取Person类的bean,并调用其setter方法:
```
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Person person = (Person) context.getBean("person");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
```
输出结果为:
```
Name: John Doe
Age: 30
```