Spring overview

IOC Brief Description

IOC (DI): Actually, the core concept of the Spring architecture does not It’s so complicated, and it’s not as obscure as described in some books. Java programmers know that: each business logic in a java program requires at least two or more objects to complete collaboratively. Generally, when each object uses its cooperative object, it needs to use something like new object(). Grammar to complete the application work of the partner. You will find that the coupling between objects is high. The idea of ​​IOC is: Spring container to realize the creation and coordination of these interdependent objects. The object only needs the relational business logic itself. From this aspect, the responsibility of how the object obtains its collaborating objects is reversed (IOC, DI), that is, the way to obtain dependent objects is reversed.

IoC and DI

   First I want to talk about IoC (Inversion of Control). This is the core of spring, throughout. The so-called IoC, for the spring framework, is spring is responsible for controlling the life cycle of objects and the relationship between objects. In traditional program development, in an object, if you want to use another object, you must get it (new one yourself, or query one from JNDI), and destroy the object after using it (such as Connection, etc.). Objects will always be coupled with other interfaces or classes.

   So how does IoC do it? The development method advocated by Spring is that all classes will be registered in the spring container, telling spring what you are and what you need, and then spring will take the initiative to give you what you want when the system is running properly, and at the same time Also hand you over to other things that need you. The creation and destruction of all classes are controlled by spring, which means that it is no longer the object that references it, but spring that controls the life cycle of an object. For a specific object, it used to control other objects, but now all objects are controlled by spring, so this is called inversion of control.

One of the key points of   IoC is During the operation of the system, it dynamically provides an object with other objects it needs. This is achieved through DI (Dependency Injection). For example, object A needs to operate the database. In the past, we always had to write code in A to obtain a Connection object. With spring, we only need to tell spring that a Connection is needed in A. As for how and when this Connection is constructed, A does not need to know. When the system is running, spring will create a Connection at an appropriate time, and then inject it into A like an injection, thus completing the control of the relationship between the various objects. A needs to rely on Connection to run normally, and this Connection is injected into A by spring. That’s how the name of dependency injection comes from. So how is DI implemented? An important feature after Java 1.3 is reflection, which allows programs to dynamically generate objects, execute methods of objects, and change properties of objects when the program is running. Spring implements injection through reflection.

Let’s let everyone know how Spring works.

 

< br />

1








2








3








4






< br />
5








6


 




public static void (String[] args) {








ApplicationContext context =


new FileSystemXmlApplicationContext(








"applicationContext.xml");








Animal animal = (Animal) context.getBean(


"animal");








animal.say();








}


First is applicationContext.xml

 




1








2
< br />






3








4








5



< br />



6


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 




























< div class="line">


```











He has a class `phz .springframework.test.Cat`











```Java


< br />




public class Cat implements Animal {








private String name;








public void say() {








System.out.println("I am "+ name + "!");








}
< br />






public void setName(String name) {








this.name = name;








}








}








```











implements `phz. springframework.test.Animal` interface











```Java


< br />




public interface Animal {








public void say();








}


Obviously the above code outputs I am kitty!

So how does Spring do it? ?
Next, let us write a Spring ourselves to see how Spring works!

First, we define a Bean class, which is used to store the attributes of a Bean

Java code
/ Bean Id /
private String id;
/ Bean Class /
private String type;
/ Bean Property /
private Map properties = new HashMap ();
[java] view plaincopy
/ Bean Id /
private String id;
/ Bean Class /
private String type;
/ Bean Property /
private Map properties = new HashMap ();

A Bean includes id, type, and Properties.

Next, Spring will start to load our configuration file and save our configuration information in a HashMap. The key of the HashMap is the Id of the Bean, and the value of the HasMap is the Bean. Only in this way can we pass The context.getBean(“animal”) method gets the Animal class. We all know that Spirng can inject basic types, and can inject types like List and Map. Next, let’s take Map as an example to see how Spring saves it.

Map configuration can be like the following

 

< br />

1








2








3








4






< br />
5








6


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 < /div>
39
 




<bean id=< span class="string">"test" class="Test">








<property name span>="testMap">








<map>








<entry key="a"> span>








<value>1


value>








entry>








<entry key="b">








<value>2


value>








entry>


< /div>





map>





< br />

property>








bean>








```











How does Spring save the above configuration? , The code is as follows:











```Java








if (beanProperty.element("map") != null) {








Map


<String, Object> propertiesMap = new HashMap< br />

<String, Object>();







< br /> Element propertiesListMap = (Elem ent) beanProperty.elements().get(0);





< br />

Iterator propertiesIterator = propertiesListMap.elements().iterator();








while (propertiesIterator.hasNext()) {








Element vet = (Element) propertiesIterator.next();








if (vet.getName(). equals("entry")) {








String key = vet.attributeValue("key");








Iterator< ?> valuesIterator = vet.elements().iterator();








while (valuesIterator.hasNext()) {





< div class="line">


Element value = (Element) valuesIterator.next();








if (value.getName().equals("value")) {
< br />






propertiesMap.put(key, value .getText());








}

< br />






if (value.getName().equals(" ref")) {







< br /> propertiesMap.put(key, new String[]{value.attributeValue("bean")});




< br />



}








}








}








}








bean. getProperties().put(name, propertiesMap);








}


Next, we will enter the core part. Let’s take a look at how Spring does dependency injection. In fact, the idea of ​​dependency injection is also very simple. It is implemented through reflection. When a class is instantiated, it The set method in the class is called by reflection to inject the class attributes stored in the HashMap into the class. Let’s see how it is done in detail.
First instantiate a class like this

 




1








2








3





< div class="line">


4








5








6


7
8
9
10
11
12
13
14
15
 




public static Object newInstance< span class="params">(String className) {








Class cls =


null;








Object obj =


null ;








< span class="keyword">try {





< br />

cls = Class.forName(className);








obj = cls.newInstance();








}


< span class="keyword">catch (ClassNotFoundException e) {








throw


new< /span> RuntimeException(e);








}


catch (InstantiationException e) {


< /div>





throw


new RuntimeException(e) ;








}


catch (IllegalAccessException e) {








throw

< br /> new RuntimeException(e);





< div class="line">


}








return obj;


< br />




}


It then injects the dependencies of this class, like this< /p>

 




1








2








3






< br />
4








5








6


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
      




public static void setProperty(Object obj, String name, String value) {








Class clazz = obj.getClass();








try {








String methodName = returnSetMthodName(name);








Method[] ms = clazz.getMethods();








for (Method m : ms) {








if (m.getName().equals(methodN ame)) {








if (m.getParameterTypes().length ==


1) {








Class clazzParameterType = m.getParameterTypes()[


0];








setFieldValue(clazzParameterType.getName(), value, m, obj);








break;








}








}








}








}


catch (SecurityException e) {








throw


new RuntimeException(e);


< br />




}


catch (IllegalArgumentException e) {








throw


new RuntimeException(e);








}


catch (IllegalAccessException e) {








throw


new RuntimeException(e);








}


catch (InvocationTargetException e) {








throw


new RuntimeException(e);








}








}


最后它将这个类的实例返回给我们,我们就可以用了。我们还是以Map为例看看它是怎么做的,我写的代码里面是创建一个HashMap并把该HashMap注入到需要注入的类中,像这样,

      




1








2








3








4








5








6


7
8
9
10
11
12

if (value

instanceof Map) {

Iterator entryIterator = ((Map) value).entrySet().iterator();

Map map =

new HashMap();

while (entryIterator.hasNext()) {

Entry entryMap = (Entry) entryIterator.next();

if (entryMap.getValue()

instanceof String[]) {

map.put((String) entryMap.getKey(),

getBean(((String[]) entryMap.getValue())[

0]));

}

}

BeanProcesser.setProperty(obj, property, map);

}

< /pre>

好了,这样我们就可以用Spring 给我们创建的类了,是不是也不是很难啊?当然Spring能做到的远不止这些,这个示例程序仅仅提供了Spring最核心的依赖注入功能中的一部分。

主要参考:

原文:大专栏  Spring概述

1

2

3

4

5

6

public static void (String[] args) {

ApplicationContext context = new FileSystemXmlApplicationContext(

"applicationContext.xml");

Animal animal = (Animal) context.getBean( "animal");

animal.say();

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

```

他有一个类`phz.springframework.test.Cat`

```Java

public class Cat implements Animal {

private String name;

public void say() {

System.out.println("I am " + name + "!");

}

public void setName(String name) {

this.name = name;

}

}

```

实现了`phz.springframework.test.Animal`接口

```Java

public interface Animal {

public void say();

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<bean id="test" class="Test">

<property name="testMap">

<map>

<entry key="a">

<value>1 value>

entry>

<entry key="b">

<value>2 value>

entry>

map>

property>

bean>

< p>```

Spring是怎样保存上面的配置呢? ,代码如下:

```Java

if (beanProperty.element("map") != null) {

Map <String, Object> propertiesMap = new HashMap <String, Object>();

Element propertiesListMap = (Element) beanProperty.elements().get(0);

Iterator propertiesIterator = propertiesListMap.elements().iterator();

while (propertiesIterator.hasNext()) {

Element vet = (Element) propertiesIterator.next();

if (vet.getName().equals("entry")) {

String key = vet.attributeValue("key");

Iterator valuesIterator = vet.elements().iterator();

while (valuesIterator.hasNext()) {

Element value = (Element) valuesIterator.next();

if (value.getName().equals("value")) {

propertiesMap.put(key, value.getText());

}

if (value.getName().equals("ref")) {

propertiesMap. put(key, new String[]{value.attributeValue("bean")});

}

}

}

}

bean.getProperties().put(name, propertiesMap);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public static Object newInstance(String className) {

Class cls = null;

Object obj = null;

try {

cls = Class.forName(className);

obj = cls.newInstance();

} catch (ClassNotFoundException e) {

throw new RuntimeException(e);

} catch (InstantiationException e ) {

throw new RuntimeException(e);

} catch (IllegalAccessException e) {

throw new RuntimeException(e);

}

return obj;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public static void setProperty(Object obj, String name, String value) {

Class clazz = obj.getClass();

try {

String methodName = returnSetMthodName(name);

Method[] ms = clazz .getMethods();

for (Method m : ms) {

if (m.getName().equals(methodName)) {

if (m.getParameterTypes().length == 1) {

Class clazzParameterType = m.getParameterTypes()[ 0];

setFieldValue(clazzParameterType.getName(), value, m, obj);

break;

}

}

}

} catch (SecurityException e) {

throw new RuntimeException(e);

} catch (IllegalArgumentException e) {

throw new RuntimeException(e);

} catch (IllegalAccessException e) {

throw new RuntimeException(e);

} catch (InvocationTargetException e) {

throw new RuntimeException(e);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

if (value instanceof Map) {

Iterator entryIterator = ((Map) value).entrySet().iterator();

Map map = new HashMap();

while (entryIterator.hasNext()) {

Entry entryMap = (Entry) entryIterator.next();

if (entryMap.getValue() instanceof String[]) {

map.put((String) entryMap.getKey(),

getBean((( String[]) entryMap.getValue())[ 0]));

}

}

BeanProcesser.setProperty(obj, property, map);

}

Leave a Comment

Your email address will not be published.