Spring 架構的簡單模擬實現

樑天超發表於2014-05-22


  Spring 架構主要有兩大特點: 

    IOC /DI: 控制反轉/依賴注入 

   AOP  切面程式設計 .

  

    今天主要是實現IOC這一特點.


    主要的邏輯如下:

    User 使用者類.

    UserDAO  User類的訪問介面. 

    UserDAOImpl  實現UserDAO 介面以實現擴充. 

    UserService  包含一系列的使用者功能 ,如addUser


   關於以上類的程式碼:

   

package com.bjsxt.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;
	}
}

 

package com.bjsxt.dao;
import com.bjsxt.model.User;


public interface UserDAO {
	public void save(User user);
}

package com.bjsxt.dao.impl;

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


public class UserDAOImpl implements UserDAO {

	public void save(User user) {
		//Hibernate
		//JDBC
		//XML
		//NetWork
		System.out.println("user saved!");
	}

}

package com.bjsxt.service;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;



public class UserService {
	private UserDAO userDAO;  
	public void add(User user) {
		userDAO.save(user);
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}

然後執行test程式碼

import com.bjsxt.dao.UserDAO;
import com.bjsxt.dao.impl.UserDAOImpl;
import com.bjsxt.model.User;
import com.bjsxt.service.UserService;
import com.bjsxt.spring.BeanFactory;
import com.bjsxt.spring.ClassPathXmlApplicationContext;


public class Test {

	public static void main(String[] args)throws Exception{
		
		
		UserService service =new UserService();
		UserDAO userdao =new UserDAOImpl();
		service.setUserDAO(userdao);
		User u =new User();
		service.add(u);
	}
}

注意這裡直接用UserDAOImpl() 來代替UserDAO , 也是體現物件導向的靈活性.  比如可以針對不同的資料庫設計不同的UserDAOImpl(). 


為了實現IOC 的裝配功能, 比如說我不想在 程式碼中體現new 的是哪種UserDAO的實現, 而是直接在配置檔案中進行設定.


配置檔案beans.xml如下:

  
<beans>
	<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl" />
	
	<bean id="userService" class="com.bjsxt.service.UserService" >
		<property name="userDAO" bean="u"/>
	</bean>
	
</beans>


這裡可以根據bean 的id  userService  找到 所屬的UserService類, 在屬性userDAO中  ,設定其為id 為 "u"的bean . 而上述檔案中的 id 為"u"的bean , 就是UserDAOImp .


當然, 需要藉助Factory 介面 和該介面的實現類 ClassPathXmlApplicationContext .


package com.bjsxt.spring;

public interface BeanFactory {
	public Object getBean(String id);
}

package com.bjsxt.spring;


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.input.SAXBuilder;

public class ClassPathXmlApplicationContext implements BeanFactory {
	
	private Map<String , Object> beans = new HashMap<String, Object>();
	
	
	//IOC Inverse of Control DI Dependency Injection
	public ClassPathXmlApplicationContext() throws Exception {
		SAXBuilder sb=new SAXBuilder();
	    
	    Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //構造文件物件
	    Element root=doc.getRootElement(); //獲取根元素HD
	    List list=root.getChildren("bean");//取名字為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 o = Class.forName(clazz).newInstance();
	       System.out.println(id);
	       System.out.println(clazz);
	       beans.put(id, o);
	       
	       for(Element propertyElement : (List<Element>)element.getChildren("property")) {
	    	   String name = propertyElement.getAttributeValue("name"); //userDAO
	    	   String bean = propertyElement.getAttributeValue("bean"); //u
	    	   Object beanObject = beans.get(bean);//UserDAOImpl instance
	    	   
	    	   String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
	    	   System.out.println("method name = " + methodName);
	    	   
	    	   Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
	    	   m.invoke(o, beanObject);
	       }
	       
	       
	    }  
	  
	}



	public Object getBean(String id) {
		return beans.get(id);
	}

}


ClassPathXmlApplicationContext 利用反射機制, 在建構函式中根據xml檔案內容實現裝配功能.

新的test函式:

import com.bjsxt.dao.UserDAO;
import com.bjsxt.dao.impl.UserDAOImpl;
import com.bjsxt.model.User;
import com.bjsxt.service.UserService;
import com.bjsxt.spring.BeanFactory;
import com.bjsxt.spring.ClassPathXmlApplicationContext;


public class Test {

	public static void main(String[] args)throws Exception{
		
		BeanFactory factory =new ClassPathXmlApplicationContext();
		
		UserService service =(UserService)factory.getBean("userService");
	//	UserDAO userdao =new UserDAOImpl();
	//	service.setUserDAO(userdao);
		User u =new User();
		service.add(u);
	}
}



相關文章