IOC的依赖注入方式有:
接口注入(不常用):定义一个注入接口,在需要注入的类中实现此接口,由于这种方法具有侵入性,所以不常用
接口UserDao.java |
package com.zhmg.spring.dao;
public interface UserDao {
public void save(String username,String password);
} |
接口UserManager.java |
package com.zhmg.spring.manager;
import com.zhmg.spring.dao.UserDao;
public interface UserManager {
public void save(String username, String password);
} |
(2)接口的不同实现
UserDao4MySqlImpl.java----对接口UserDao的实现 |
package com.zhmg.spring.dao;
public class UserDao4MySqlImpl implements UserDao {
public void save(String username, String password) {
System.out.println("使用MySql时对UserDao的实现"); } }
|
UserDao4OracleImpl.java----对接口UserDao的实现 |
package com.zhmg.spring.dao;
public class UserDao4MySqlImpl implements UserDao {
public void save(String username, String password) {
System.out.println("使用Oracle时对UserDao的实现"); } }
|
UserManagerImpl.java----对UserManager接口的实现 |
package com.zhmg.spring.manager;
import com.zhmg.spring.dao.UserDao;
public class UserManagerImpl implements UserManager {
public UserDao userDao = null;
public void save(String username, String password) { this.userDao.save(username, password); }
public void setUserDao(UserDao userDao) { this.userDao = userDao; }
} |
(3)applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="userDao4MySql" class="com.zhmg.spring.dao.UserDao4MySqlImpl"/>
<bean id="userDao4Oracle" class="com.zhmg.spring.dao.UserDao4OracleImpl"/>
<bean id="userManager" class="com.zhmg.spring.manager.UserManagerImpl"> <constructor-arg ref="userDao4MySql"/> </bean> </beans>
|
(4)测试结果
package com.zhmg.spring.client;
import org.springframework.beans.factory.BeanFactory; import com.zhmg.spring.dao.UserDao4OracleImpl; import com.zhmg.spring.manager.UserManagerImpl;
public class Client { public static void main(String []agrs){ BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); UserManager userManager = (UserManager)factory.getBean("userManager"); userManager.save("测试", "123"); } } |
使用MySql时对UserDao的实现 |
(5)总结
使用Spring时并不需要继承Spring的任何类或者接口(轻量级的一种体现),使得程序的层次更加分明,程序的耦合度降低,侵入性降低,因此程序便于维护,复用率更高。即使当初使用了Sping进行的设计,以后需要用其他技术代替Spring对程序的影响不是很大
----------此实例的设计思想以及大部分代码来自北京尚学堂