spring用setter注入的方式
时间: 2023-09-03 22:15:20 浏览: 54
Spring使用setter方法注入依赖对象,具体步骤如下:
1. 在需要注入依赖的类中,编写一个setter方法,方法名通常以set开头,后面跟着依赖的属性名,如:
```
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
```
2. 在Spring配置文件中,配置依赖对象的bean,如:
```
<bean id="personDao" class="com.example.PersonDaoImpl"></bean>
```
3. 在需要注入依赖的类的bean配置中,使用property元素指定要注入的依赖属性,如:
```
<bean id="personService" class="com.example.PersonServiceImpl">
<property name="personDao" ref="personDao"></property>
</bean>
```
其中,name属性指定要注入的属性名,ref属性指定要注入的依赖对象的bean id。
4. 在应用程序中,使用ApplicationContext接口获取需要注入依赖的类的bean实例,如:
```
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
PersonService personService = (PersonService) context.getBean("personService");
```
此时,personService对象的personDao属性已经被注入了PersonDaoImpl对象。