项目结构
程序示图
如果想要使用MysqlImpl,只需要修改配置文件即可
这个过程就叫控制反转 :
- 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
- 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .
- 依赖注入 : 就是利用set方法来进行注入的.
配置文件和测试类代码如下:
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mysqlImpl" class="com.kuang.dao.UserDaoMysqlImpl"/>
<bean id="oracleImpl" class="com.kuang.dao.UserDaoOracleImpl"/>
<bean id="userServiceImpl" class="com.kuang.service.UserServiceImpl">
<!--
ref:引用Spring中创建好的对象
value:基本数据类型
-->
<property name="userDao" ref="mysqlImpl"/>
</bean>
</beans>
import com.kuang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext,拿到Spring容器
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl =
(UserServiceImpl)context.getBean("userServiceImpl");
userServiceImpl.getUser();
}
}