文章目录
项目结构:
程序示图:
如果想使用MysqlImpl 只需要修改配置文件即可
执行测试:
这个过程就叫做控制反转
控制:谁来控制对象的创建?传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spirng来创建的。
反转:程序本身不创建对象了,从主动创建对象,转变成被动接收对象。
依赖注入:就是复用set方法进行注入(即为属性赋值)
一句话描述IOC:对象由Spring创建,管理,装配。
配置文件和测试类代码如下:
<?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.blackcat.dao.UserDaoMysqlImpl"/>
<bean id="oracleImpl" class="com.blackcat.dao.UserDaoOracleImpl"/>
<bean id="UserServiceImpl" class="com.blackcat.service.UserServiceImpl">
<property name="userDao" ref="mysqlImpl"/>
</bean>
</beans>
package com.blackcat;
import com.blackcat.dao.UserDaoImpl;
import com.blackcat.dao.UserDaoMysqlImpl;
import com.blackcat.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void testUser(){
//用户实际调用的是业务层,dao层他们不需要接触!
// UserServiceImpl userService = new UserServiceImpl();
// userService.setUserDao(new UserDaoImpl());
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}