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