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监听启动加载