Spring - 如何实现IOC

Spring 两大核心特性IOC和AOP.IOC的概念就不再赘述了,那IOC是如何实现的呢?今天写了一个简单的模拟。

项目划分为四层,DAO(interface和impl)->Service->Spring->Test

1.1DAO Interface

package com.wicresoft.dao;

import com.wicresoft.model.User;

public interface UserDAO {
	public boolean Save(User user);
}

1.2 DAO Impl

1) UserDAPImpl.java

package com.wicresoft.daoImpl;

import com.wicresoft.dao.UserDAO;
import com.wicresoft.model.User;

public class UserDAOImpl implements UserDAO {
	public boolean Save(User user){
		System.out.println("UserDAOImpl:user saved.");
		return true;
	}
}
2) UserDAOImpl2.java
package com.wicresoft.daoImpl;

import com.wicresoft.dao.UserDAO;
import com.wicresoft.model.User;

public class UserDAOImpl2 implements UserDAO {
	public boolean Save(User user){
		System.out.println("UserDAOImpl2:user saved.");
		return true;
	}
}
2.Service

package com.wicresoft.service;

import com.wicresoft.dao.UserDAO;
import com.wicresoft.daoImpl.UserDAOImpl;
import com.wicresoft.model.User;

public class UserService {
	
	private UserDAO userDAO = new UserDAOImpl();
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public boolean Add(User user){
		return this.userDAO.Save(user);
	}
}
3.Spring

1) BeanFactory interface

package com.wicresoft.spring;

public interface BeanFactory {
	Object getBean(String name);
}
2) ApplicationContext

package com.wicresoft.spring;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.wicresoft.util.Sample1;

public class ClassPathXmlApplicationContext implements BeanFactory {

	private Map<String,Object> beans = new HashMap<String,Object>();
	
	@SuppressWarnings("unchecked")
	public ClassPathXmlApplicationContext(){
		SAXBuilder sb = new SAXBuilder();
	    Document doc;
		try {
			doc = sb.build(Sample1.class.getClassLoader().getResourceAsStream("beans.xml"));
			Element root=doc.getRootElement(); 
		    List<Element> list=root.getChildren("bean");
		    for(int i=0;i<list.size();i++){
		       Element element=(Element)list.get(i);
		       String id = element.getAttributeValue("id");
		       String clazz=element.getAttributeValue("class");
		       Object object = Class.forName(clazz).newInstance();
		       System.out.println(id);
		       System.out.println(clazz);
		       beans.put(id, object);
		       for(Element propertyElement : (List<Element>)element.getChildren("property")) {
		    	   String name1 = propertyElement.getAttributeValue("name"); 
		    	   String bean = propertyElement.getAttributeValue("bean"); 
		    	   Object beanObject = beans.get(bean);
		    	   
		    	   String methodName = "set" + name1.substring(0, 1).toUpperCase() + name1.substring(1);
		    	   System.out.println("method name = " + methodName);
		    	   
		    	   Method method = object.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
		    	   method.invoke(object, beanObject);
		       }
		    }
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Object getBean(String name) {
		return beans.get(name);
	}
}
4.Test

package com.wicresoft.test;
import junit.framework.Assert;

import org.junit.Test;
import com.wicresoft.dao.UserDAO;
import com.wicresoft.daoImpl.UserDAOImpl;
import com.wicresoft.model.User;
import com.wicresoft.service.UserService;
import com.wicresoft.spring.BeanFactory;
import com.wicresoft.spring.ClassPathXmlApplicationContext;
import com.wicresoft.daoImpl.UserDAOImpl2;

public class UserSerciceTest {

	private UserDAO userDAO;
	private UserService userService;
	private User user;
	
	@Test
	public void test1() {
		
		userService = new UserService();
		
		user = new User();
		user.setUsername("admin");
		user.setPassword("1234");
		Assert.assertEquals(true, userService.Add(user));
	}
	
	@Test
	public void test2() {
		
		userService = new UserService();
		userDAO = new UserDAOImpl2();
		
		userService.setUserDAO(userDAO);
		user = new User();
		user.setUsername("admin");
		user.setPassword("1234");
		Assert.assertEquals(true, userService.Add(user));
	}
	
	@Test
	public void test3() {
		
		BeanFactory applicationContext = new ClassPathXmlApplicationContext();
		UserService service = (UserService)applicationContext.getBean("userService");
		
		User u = new User();
		u.setUsername("administrator");
		u.setPassword("1234");
		service.Add(u);
	}
}
5.Model

package com.wicresoft.model;

public class User {
	
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}
6.beans.xml

<beans>
	<bean id="userDAO" class="com.wicresoft.daoImpl.UserDAOImpl2" />
	<bean id="userService" class="com.wicresoft.service.UserService" >
		<property name="userDAO" bean="userDAO"/>
	</bean>
</beans>
7.输出结果

UserDAOImpl:user saved.
UserDAOImpl2:user saved.
dao
com.wicresoft.daoImpl.UserDAOImpl2
userService
com.wicresoft.service.UserService
method name = setUserDAO
UserDAOImpl2:user saved.
总结:

该Demo中核心的类就是ClassPathXmlApplicationContext,该类根据配置文件读取配置,然后创建类的实例,调用set方法,将其注入到高层对象。

这种做法在structs2中,我们的Action继承自ActionSupport的时候,我们只需要实现Action里面的set即可获取页面上的值,实现方式也是这样的。

一个典型的继承自ActionSupport的Action如下:

public class StudentAction extends ActionSupport {
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	public String Add() {
		System.out.println("StudentAction add executed.");
		System.out.println("name:" + name);
		System.out.println("age:" + age);
		return SUCCESS;
	}
	public String delete() {
		return SUCCESS;
	}
}
在页面上,我们可以通过如下方式传值:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    This is my JSP page. 
    <br>
    <a href="actions/Student!Add?name='admin'&age=12345">Add User</a>
    
  </body>
</html>
在ActionSupport中也是通过这种IOC的机制来实现获取页面传过来的值的,具体是在org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter这个核心filter中拦截请求,然后把参数传递给ActionSupport来实现的。

具体见web.xml中的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Struts Blank</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
IOC在spring和struts2中均十分常见,对于设计灵活的架构具有非常重要的参考意义。










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值