Automatically implement Spring's IOC

1. Basic concepts of IOC

IoC (Inversion of Control), intuitively speaking, is that the control right of object creation or search object dependency is transferred from application code to the external container, and the transfer of control right is the so-called inversion. With Ioc, other objects that an object depends on will be passed in in a passive way, instead of creating or finding dependent objects by the object itself.

2. Examples of IOC scenarios

Lisa is already big and young, and has never had a boyfriend. Seeing other people's love and affection, she couldn't help but want to find a BoyFriend. There are three options before her: take the initiative to "encounter" Or introduced by a colleague or arranged by her parents. Which one would she choose?

imageThe second plan, introduced by colleagues or arranged by parents,

image

Although in real life we ​​all hope to have a perfect encounter with our significant other, in the Spring world, like Lisa, the choice is arranged by our parents. It is the reversal of control, and here are the parents who have control. , Is the so-called container concept of Spring.

Three, IOC code implementation

The code structure is shown in the figure below

Define POJO class

package org.springioc;
public class Student {

 private String name;
 private String add;
 
 public void selfIntroDuction(){
 System.out.println("我的姓名是 " + name + " 我来自 " + add);
 
 }
 
 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getAdd() {
 return add;
 }

 public void setAdd(String add) {
 this.add = add;
 }
 
}

Define Service

package org.springioc;

public class StudentService {
 private Student student;

public Student getStudent() {
 return student;
}

public void setStudent(Student student) {
 this.student = student;
}
 
}

Define the configuration file and write the above 2 types of information into it

<?xml version="1.0" encoding="UTF-8"?>

<beans>
 <bean id="Student" class="org.springioc.Student">
 <property name="name" value="Hover"/>
 <property name="add" value="China"/>
 </bean>

 <bean id="StudentService" class="org.springioc.StudentService">
 <property ref="Student"/>
 </bean>
</beans>

定义ApplicationContext接口

package org.springioc;

public interface ApplicationContext {
 /**
 * 获取bean
 * @param string
 * @return
 */
 Object getBean(String string);

}

接口的实现类,加载配置文件,并且解析xml,将bean注入到map

package org.springioc;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class ClassPathXMLApplicationContext implements ApplicationContext{
 //文件加载
 private File file;
 //bean容器
 private ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();
 //构造函数
 public ClassPathXMLApplicationContext(String config_file) {
 URL url = this.getClass().getClassLoader().getResource(config_file);
 try {
 file = new File(url.toURI());
 XMLParsing();
 } catch (Exception e) {
 e.printStackTrace();
 }
 
 }
 /**
 * 解析xml,并且将bean 注册到map
 * @throws Exception
 */
 private void XMLParsing() throws Exception { 
 SAXBuilder builder = new SAXBuilder();
 Document doc = builder.build(file);
 XPath xpath = XPath.newInstance("//bean");
 List beans = xpath.selectNodes(doc);
 Iterator i = beans.iterator();
 while (i.hasNext()) {
 Element bean = (Element) i.next();
 String id = bean.getAttributeValue("id");
 String cls = bean.getAttributeValue("class");
 Object obj = Class.forName(cls).newInstance();
 Method[] method = obj.getClass().getDeclaredMethods();
 List<Element> list = bean.getChildren("property");
 for (Element el : list) {
 for (int n = 0; n < method.length; n++) {
 String name = method[n].getName();
 String temp = null;
 if (name.startsWith("set")) {
 temp = name.substring(3, name.length()).toLowerCase();
 if (el.getAttribute("name") != null) {
 if (temp.equals(el.getAttribute("name").getValue())) {
 method[n].invoke(obj, el.getAttribute("value").getValue());
 }
 } else {
 method[n].invoke(obj,map.get(el.getAttribute("ref").getValue()));
 }
 }
 }
 }
 map.put(id, obj);
 }
 }

 public Object getBean(String name) {
 return map.get(name);
 }

}

POM.xml配置文件

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <modelVersion>4.0.0</modelVersion>
 <parent>
 <groupId>cn.maxap</groupId>
 <artifactId>search-parent</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 </parent>
 <groupId>cn.maxap</groupId>
 <artifactId>springioc</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>springioc</name>
 <url>http://maven.apache.org</url>
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
 <dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <!-- https://mvnrepository.com/artifact/jdom/jdom -->
<dependency>
 <groupId>jdom</groupId>
 <artifactId>jdom</artifactId>
 <version>1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
<dependency>
 <groupId>jaxen</groupId>
 <artifactId>jaxen</artifactId>
</dependency>

 
 </dependencies>
</project>

测试类

package org.springioc; 

public class Test { 
 public static void main(String[] args) { 
 //Load the resource file and parse the bean into the map 
 ApplicationContext context = new ClassPathXMLApplicationContext("application.xml"); 
 //Get bean 
 StudentService stuServ = (StudentService) context.getBean("StudentService"); 
 //Call method 
 stuServ.getStudent().selfIntroDuction(); 
 } 
 
}

Output result

My name is Hover and I am from China


Guess you like

Origin blog.51cto.com/15082402/2644347