JAVA:IOC原理

JAVA:IOC原理

1.IOC的基础知识背景

IoC理论的背景:在采用面向对象方法设计的软件系统中,底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑。

2.什么是IOC

IoC是Inversion of Control的缩写,翻译成“控制反转”,即控制不再有对象之间相互调用进行,而是有IOC容器进行,模块只需要做好自己就行。

3.IOC的原理

控制反转是spring框架的核心,也就是说,所有的组件都是被动的,所有的组件初始化和调用都由容器负责。组件处在一个容器当中,由容器负责管理。简单的来讲,就是由容器控制程序之间的关系,而非传统实现中,由程序代码直接操控,即在一个类中调用另外一个类。这也就是所谓“控制反转”的概念所在:控制权由应用代码中转到了外部容器,控制权的转移,即所谓反转。

4.ioc代码实现

编写ApplicationContext:

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ApplicationContext {
	
	private Hashtable<String, Object> container = new <String, Object> Hashtable();
	
	public void xmlInit(String fileName) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		
			Document  doc = db.parse(new FileInputStream(fileName));
			
			Node root = doc.getDocumentElement();
			NodeList childList = root.getChildNodes();
			for(int i=0;i<childList.getLength();i++) {
				
				Node childNode = childList.item(i);
				
				NamedNodeMap nodeAttributes = childNode.getAttributes();
				
				if(nodeAttributes != null && nodeAttributes.getLength() > 0) {
					Node clazz = nodeAttributes.getNamedItem("class");
					Node id    = nodeAttributes.getNamedItem("id");
					if(clazz != null && id != null) {
						String className = clazz.getNodeValue();
						String idName    = id.getNodeValue();
						System.out.println(className);
						System.out.println(idName);
					
						Object obj = Class.forName(className).newInstance();
					
						container.put(idName, obj);
					}
				}				
			}
			
		} catch (ParserConfigurationException | SAXException | IOException e) {
		
			e.printStackTrace();
		}
	}
	
	public Object getBean(String id) throws IllegalArgumentException, IllegalAccessException {
		Object obj = this.container.get(id);
		
		
		Field[] fields = obj.getClass().getDeclaredFields();
		for(Field field: fields) {
			if(field.isAnnotationPresent(AutoWired.class)) {
			
				field.setAccessible(true);
		
				field.set(obj, this.container.get(field.getName()));
			}
		}
		
		return obj;
	}
	
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		// TODO Auto-generated method stub
		ApplicationContext applicationContext = new ApplicationContext();
		String path = ApplicationContext.class.getResource("/").getPath();
		applicationContext.xmlInit(path + "applicationContext.xml");
		
		
		User user = (User)applicationContext.getBean("user");
		
		UserController userController = (UserController)applicationContext.getBean("userController");
		userController.login("zhangsan", "123456");
	}

}

创建自动连接AutoWired:

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target({ FIELD })

public @interface AutoWired {

}

用户类:

public class User {
	private String userName;
	private String userPwd;
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
}

创建用户控制:

public class UserController {
	@AutoWired
	private UserService userService;
	
	public void login(String userName, String userPwd) {
		userService.getUser();
	}
}

创建用户服务:

public class UserService {
	public User  getUser() {
		System.out.println("ll");
		return new User();
	}
}

总结:

  • Spring IOC容器主要有继承体系底层的BeanFactory、高层的ApplicationContext和WebApplicationContext
  • Bean有自己的生命周期
  • Spring应用的IOC容器通过tomcat的Servlet或Listener监听启动加载
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值