Spring 中Ioc(控制反转) 用例
IoC全名Inversion of Control,中文称“控制反转”。和AOP一样,是Spring的核心技术。
这里举个例子,这说明一下IoC的应用。
接口 UserDao.java:
1 package com.springdemo.dao;
2
3 public interface UserDao {
4 public void save(String name,String password);
5 }
类 UserDaoImplForMysql.java:
代码
1 package com.springdemo.dao;
2
3 public class UserDaoImplForMysql implements UserDao {
4
5 public void save(String name, String password) {
6 System.out.println("UserDaoImplForMysql.....");
7 }
9 }
类 UserDaoImplForOrcle.java:
代码
1 package com.springdemo.dao;
2
3 public class UserDaoImplForOrcle implements UserDao {
4
5 public void save(String name, String password) {
6 System.out.println("UserDaoImplForOrcle...");
7 }
9 }
客户端类 Client.java:
代码
1 package com.springdemo.client;
2
3 import com.springdemo.dao.UserDaoImplForMysql;
4 import com.springdemo.manager.UserManagerImpl;
5
6 public class Client {
7 public static void main(String[] args) {
8 UserManagerImpl userManager = new UserManagerImpl();
9 userManager.setUserDao(new UserDaoImplForMysql());
10 userManager.save("pxl", "pxl123");
18 }
19 }
这里,如果想改用UserDaoImplForOrcle.java类,必须修改客户端代码。
下面引入IoC这重新实现客户。
配置Spring容器 bean.xml:
代码
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
3 xmlns:util="http://www.springframework.org/schema/util"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
6 http://www.springframework.org/schema/context
7 http://www.springframework.org/schema/context/spring-context-3.0.xsd
8 http://www.springframework.org/schema/util
9 http://www.springframework.org/schema/util/spring-util-3.0.xsd">
10
11 <bean id="UserDaoImplForMysql" class="com.springdemo.dao.UserDaoImplForMysql" />
12 <bean id="UserDaoImplForOrcle" class="com.springdemo.dao.UserDaoImplForOrcle" />
13 <bean id="UserManagerImpl" class="com.springdemo.manager.UserManagerImpl">
14 <property name="userDao" ref="UserDaoImplForMysql"/>
15 </bean>
16
17 </beans>
修改客户端类 Client.java:
代码
1 package com.springdemo.client;
2
3 import org.springframework.beans.factory.BeanFactory;
4 import org.springframework.context.support.ClassPathXmlApplicationContext;
5 import com.springdemo.manager.UserManagerImpl;
6
7 public class Client {
8 public static void main(String[] args) {
9 // UserManagerImpl userManager = new UserManagerImpl();
10 // userManager.setUserDao(new UserDaoImplForMysql());
11 // userManager.save("pxl", "pxl123");
12
13 BeanFactory fac = new ClassPathXmlApplicationContext("bean.xml");
14 UserManagerImpl userDao = (UserManagerImpl) fac.getBean("UserManagerImpl");
15 userDao.save("pxl", "pxl123");
18 }
19 }
这样若想改用UserDaoImplForOrcle.java类,只须配置一下bean.xml文件即可。