I. Basic concepts of IOC

IoC(Inversion of Control), intuitively speaking, is the object creation or search object dependent Control from the application code to the external container, the transfer of Control is called Inversion. With Ioc, other objects that an object depends on are passed in passively, rather than being created or found by the object itself.

2. Examples of IOC scenarios

Lisa was old enough to have no BoyFriend all the time, so she could not help looking for a BoyFriend. She had three options open to her: a spontaneous encounter, an introduction from a colleague, Or her parents. Which one will she choose?

The second option is to be introduced by colleagues or arranged by parents.

While in real life we all want perfect encounters with our significant other, in the Spring world, like Lisa, it’s all about the parents, the inversion of control, and the controlling parent is what Spring calls the container concept.

IOC code implementation

The code structure is shown below

Define the POJO class

package org.springioc;
public class Student {

 private String name;
 private String add;
 
 public void selfIntroDuction(){
 System.out.println("My name is." + name + "I'm from" + 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; }}Copy the code

Defining a Service

package org.springioc;

public class StudentService {
 private Student student;

public Student getStudent() {
 return student;
}

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

Define the configuration file to write the above two class information

<? 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>Copy the code

Define the ApplicationContext interface

package org.springioc; Public interface ApplicationContext {/** * get bean * @param string * @return
 */
 Object getBean(String string);

}Copy the code

The implementation class of the interface, loads the configuration file, and parses the XML to inject the bean into the 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 {/ / File loading private File File; Private ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>(); private ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>(); / / the constructor 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(); }} /** * parse XML, And register the bean with 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) {
 returnmap.get(name); }}Copy the code

Pom.xml configuration file

<? 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> < version > 0.0.1 - the SNAPSHOT < / version > < / parent > < groupId > cn. Maxap < / groupId > < artifactId > springioc < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < name > springioc < / name > < url > http://maven.apache.org < / url > < properties > <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> < the 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> The < version > 1.1 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/jaxen/jaxen --> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> </dependency> </dependencies> </project>Copy the code

The test class

package org.springioc; Public class Test {public static void main(String[] args) { And parsing bean into the map ApplicationContext context = new ClassPathXMLApplicationContext ("application.xml"); StudentService stuServ = (StudentService) context.getBean(StudentService)"StudentService"); // Call the method stUserV.getStudent ().selfintroduction (); }}Copy the code

The output

My name is Hover. I come from China

Project code has been uploaded to https://gitee.com/jxuasea/maxap/tree/master/springioc