使用set方法注入对象属性
编写UserDao.java文件
package com.example.spring; public class UserDao {
public void print(){
System.out.println("Dao print.");
}
}
编写UserService.java文件
package com.example.spring; public class UserService {
//1、定义dao类型属性
private UserDao userDao;
//2、生成set方法
public void setUserDao(UserDao userDao){
this.userDao = userDao;
} public void print(){
System.out.println("Service print.");
//如果不使用Spring对象属性注入的方式,想在service中调用dao里面的方法,必须先new一个dao的对象
//UserDao dao = new UserDao();
//dao.print();
userDao.print();
}
}
编写Beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="com.example.spring.UserDao"></bean> <bean id="userService" class="com.example.spring.UserService" >
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
注意注入的属性是UserDao类的id。
编写Application.java
package com.example.spring; import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application {
public static void main(String[] args) {
//bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml
//使用AbstractApplicationContext容器
AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");
//得到配置创建的对象
UserService userService = (UserService) context.getBean("userService");
userService.print();
}
}
运行输出
Service print.
Dao print.