基础篇——在MyEclipse中搭建Spring
搭建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、执行结果如下: