标签:demo 更换 ring 配置 string 上下文 depend mss sys
本文基于示例的方式解释控制反转,再看控制反转之前,我们先看下常规控制流程,以数据库访问为例
示例并没有实际访问数据,而是基于service和dao,模拟请求数据
注意:本实例基于Idea开发工具
public interface UserDao {
String getUser();
}
public class UserDaoMSSqlImpl implements UserDao {
public String getUser() {
return "从SQL Server查询用户";
}
}
public class UserDaoMySqlImpl implements UserDao {
public String getUser() {
return "从MySQL查询用户";
}
}
public interface UserService {
void getUser();
}
public class UserServiceImpl implements UserService {
// 如果想更换数据库,这个地方需要改一下
private UserDao userDao = new UserDaoMSSqlImpl();
public void getUser() {
System.out.println(userDao.getUser());
}
}
public class UserTest {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
从上面的例子中看到,如果想更改数据连接,必须修改代码,也就是service类中,更新dao的初始化
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
</dependencies>
<?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="mssqlImpl" class="com.example.dao.UserDaoMSSqlImpl"></bean>
<bean id="mysqlImpl" class="com.example.dao.UserDaoMySqlImpl"></bean>
<bean id="userServiceImpl" class="com.example.service.UserServiceImpl">
<!-- 更新ref:mssqlImpl或mysqlImpl,即可实现数据库切换 -->
<property name="userDao" ref="mysqlImpl"></property>
</bean>
</beans>
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void getUser() {
System.out.println(userDao.getUser());
}
// 程序被动接受入口,依赖注入就是利用set方法注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
public class UserTest {
public static void main(String[] args) {
// 获取Spring上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml");
UserService userService1 = (UserService)context.getBean("userServiceImpl");
userService1.getUser();
}
}
从上面两个示例里面看出:
标签:demo 更换 ring 配置 string 上下文 depend mss sys
原文地址:https://www.cnblogs.com/honzhez/p/13418219.html