搭建Spring: 3、演示IOC操作,在Service中調用Dao中的方法 UserDao.java package com.zzb.www.dao public class UserDao{ public void add(){ System.out.println("dao........") ...
搭建Spring:
3、演示IOC操作,在Service中調用Dao中的方法
UserDao.java
package com.zzb.www.dao
public class UserDao{
public void add(){
System.out.println("dao........");
}
}
UserService.java
package com.zzb.www.service
public class UserService{
//定義Dao類型屬性
private UserDao userDao;
//生成set方法
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
public void add(){
System.out.println("service........");
userDao.add();
}
}
4、找到Spring的核心配置文件
配置文件applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 註入對象類型屬性 -->
<!-- 配置service和dao對象 -->
<bean id="userDao" class="com.zzb.www.UserDao"></bean>
<bean id="userService" class="com.zzb.www.UserService">
<!-- 註入dao對象
name屬性值:service類裡面屬性名稱
ref屬性:dao配置bean標簽中id值 -->
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
5、然後編寫測試類SpringTest.java:
package com.zzb.www.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest{
@Test
public void testUser() {
//1 載入spring配置文件,根據創建對象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//2 得到配置創建的對象
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
6、執行結果如下: