spring-测试IOC创建对象
1.编写UserDao接口
public interface UserDao {
public void getUser();
}
2.给UserDao编写两个对应的实现类
public class UserDaoMysqlImpl implements UserDao{
@Override
public void getUser() {
System.out.println("Mysql获取用户数据");
}
}
public class UserDaoOracleImpl implements UserDao{
@Override
public void getUser() {
System.out.println("Oracle获取用户数据");
}
}
3.编写UserService接口
public interface UserService {
void getUser();
}
4.编写UserService的实现类
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
5.编写配置文件,将需要创建的对象注册在配置文件中
首先是通过mysqlImpl实现,只需要将mysqlImpl注入到UserServiceImpl中的UserDao属性
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mysqlImpl" class="com.lv.dao.UserDaoMysqlImpl"/>
<bean id="oracleImpl" class="com.lv.dao.UserDaoOracleImpl"/>
<!-- ref : 引用Spring容器中创建好的对象
value : 具体的值,基本数据类型
-->
<bean id="UserServiceImpl" class="com.lv.service.UserServiceImpl">
<property name="userDao" ref="mysqlImpl"/>
</bean>
</beans>
6.测试
6.1测试代码
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext : 拿到spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//拿到容器后,需要什么,就用容器get什么
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
6.2.执行结果
7.修改UserDao的实现类
7.1修改配置文件
通常修改一个接口的实现类需要重新new一个新的实现类,相当于更改了程序本身,使用IOC之后只需要修改配置文件就可以,将配置文件中UserServiceImpl的UserDao属性注入更改为oracleImpl
<bean id="UserServiceImpl" class="com.lv.service.UserServiceImpl">
<property name="userDao" ref="oracleImpl"/>
</bean>
测试代码不需要改变
7.2执行结果