Categories
Uncategorized

Spring Framework learning Notes (1) – IOC and dependency inversion control injection DI

The main role of the Spring Framework, is to provide a container, the container can create and manage objects. For example, Dao etc., or a class with multiple dependencies (includes Teacher Student class member variable of the class)

Spring has two core concepts, a reverse control (the IOC, called the Inverse of Control), the other is Oriented Programming (the AOP, called the Aspect Oriented Program)

Spring Framework is the most widely used Java application framework, and its success comes from the concept, not the technology itself, which includes the concept of IoC (Inversion of Control, IoC) and AOP (Aspect Oriented Programming, Aspect Oriented Programming)

Spring’s fundamental mission: to simplify Java development

Spring framework suitable for all Java programs

Architecture consists of:

Concepts

Inversion of Control, from another point of view, and can be called dependency injection (DI, called the Dependency Injection), will be explained later, to say here about the concept.

Now we come to understand the idea of ​​Inversion of Control by two angles, may differ from the understanding, for reference only

Code explanation angle

Case 1: According to our general programming, if we want to get an object, you have a configuration method of this class, passing appropriate parameters (resources), we can get this object.

However, in some cases, such operations will make the code is too complicated and miscellaneous (each time you need an object to be used once the new keyword), and does not facilitate the management of resources.

Case 2: For this situation, we can consider creating a class factory to be optimized, then we can call getXX factory class method, the parameters (resources) passed into the method, to obtain the required object.

Case 3: The above situation is better than some of our regular programming, however, management of resources or some inconvenient, so this time there will be a Spring, help us to manage resources, Spring can also be seen as a big factory, It includes the management of resources.

Inversion of Control means is that, we had to create their own objects using the new keyword (our control to create the object) becomes the Spring automatically create objects (control objects created Spring)

A practical point of explanation:

For example, we want to eat, and then use their own resources (bought vegetables, rice) for cooking, but also after dinner leftovers for processing (the fridge or drained), which is resource management, which 1 is equivalent to the case.

Our own to buy food, to buy rice, to the mother or restaurant, or her mother cook for our hotel, which is similar to the role of mother and factory class hotel, but we can not manage leftovers (assuming the mother is not to we intervene deal with leftovers, hotel and certainly will not let you intervene), this is the situation 2

We are not going to buy food and buy rice directly to the hotel or the hotel for dinner, after dinner and regardless of the rest of the vegetables and rice is how to deal with (handled by a restaurant or hotel), where the restaurants and hotels Spring is the equivalent role, restaurants and hotels have leftovers processing (automatic resource management), which is equivalent to the case 3

getting Started

Environment Configuration

Spring framework jar package more, we can choose according to demand, the following list and description of common jar package

file name

Explanation

Using Spring’s AOP features needed for library

It contains an access profile, create and manage bean as well as IoC / DI operation of all related classes

Spring provides a number of extensions to the core

Spring Framework core library, the various components of Spring is to be used to this kind of package

Spring expression language required libraries

a spring built-in unit test

spring-aop.jar
spring-beans.jar
spring-context.jar
spring-core.jar
spring-expression.jar
spring-test.jar

I use Maven configuration, I am here to spring dependent jar package are using the latest, all versions will be able to directly input RELEASE


        
            junit
            junit
            4.11
            test
        
        
            commons-logging
            commons-logging
            RELEASE
        
        
            org.springframework
            spring-context
            RELEASE
        
        
            org.springframework
            spring-test
            RELEASE
        
        
            org.springframework
            spring-core
            RELEASE
        
        
            org.springframework
            spring-beans
            RELEASE
        
        
            org.springframework
            spring-aop
            RELEASE
        
        
            org.springframework
            spring-expression
            RELEASE
        
    

demand

Suppose now need a Student class, student number and Student have names, but also includes a Teacher class, we generate the object by the Spring container

Entity class

Student.java

public class Student{
    private String sname;
    private String sno;
    private Teacher teacher;
    //省略get/set方法
}

Teacher.java

public class Teacher{
    private String tname;
    private String tno;
    //省略get/set方法
}

spring Profiles

The use of the maven, therefore, the xml configuration file in the resources folder, then automatically maven these configuration files in the right place

Name spring configuration file can take any

spring-config.xml



       
    
        
        
    
    
    
        
        
        
        
    

Obtain an object

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//这里的参数student就是上面的配置文件Student对象的id,需要强转
Student s = (Student) context.getBean("student");

Analysis and supplement

Briefly analyze the above example, spring container will automatically call the constructor entity class, generating a student object, and then, the set is provided by a method defined xml attribute values ​​to the object.

Thereafter, to obtain a student object through the spring containers

Profiles additional knowledge

bean tag

Property / sub-tab

Explanation

A unique identifier used to represent the only bean

Type (the package name + class name) of an object

Subtag bean tag, an attribute of the object

id
class
property

property label

Property / sub-tab

Explanation

Attribute name (attribute name and the same class), it will actually be reflected by calling the property set methods setXx

Attribute value for assignment to the simple types, simple types (int, double, string)

Attribute value for custom type assignment, for example, above we Teacher Student contains a class attribute is a reference to another bean id

name
value
ref

PS: If the class has a property type is an interface, but also using the ref attribute, the bean class reference implementation of this interface id

Dependency Injection DI

Introduction

Inversion of Control and the Dependency injection concept are the same, but viewed from different perspectives

We view the Student class, Student class has several attributes, we through spring configuration file, the attribute value (resources) Student injected into the object, which is called dependency injection

Three ways dependency injection

1.settter set value of the injected

This method is to call the method setXx essentially reflected by the object to set values, Spring firstly no entity class constructor parameter to a new object is then set to the value set by the method of the object.

Therefore, the premise of this method is to ensure that the set method and a corresponding constructor parameter attributes presence or absence of the entity class (Java Bean can follow various specification)



2. constructor injection

To use this method of construction according to the order of the parameters


    
    

If you do not want in the order, you can use the index property


    
    

If there are two constructors are only two parameters, but the parameters of different types, you can use the type attribute


    
    

Using custom data, and also prior to using the ref attribute


    

3. p namespace injection

Using this method can be more convenient, you can use the same property tag, but the use of p: attribute name or p: attribute name -ref

Before use, was added in the spring configuration file

xmlns:p="http://www.springframework.org/schema/p"

Injection of various types of data attributes

Before using the value attribute, value tags may also be used, use the type defined type


    

xml file, <& are="" special="" symbols,="" and,="" in="" particular,="" be="" prepared="" by="" way="" of="" input<="" p=""/>

There are two ways, one is to use xml predefined entity references, and second, using

value labels, there are two ways to say above, while the value attribute only xml predefined entity references

& -> &

< -> <

is set to null



    
    张&三





Collection Type

You can use the set list, map, set tag

Types of

label

List or array

Tag list using outer, inner layer with a value or ref

Using the outer set labels, the inner layer or value ref

Use outer map, intermediate layer entry, the innermost layer is formed using the key and value tags

Properties Resource File

Layer using props, the sub-label prop

Set
Map

    
        数值
        
    



    
        
            数值
        
        
        
    




    2

PS: Remember ref value and two labels assigned to it, value assigned to the basic types, ref to customize the type of assignment

example:

MyArray.java

package com.wan;

import java.util.List;

/**
 * @author StarsOne
 * @date Create in  2019/9/24 0024 15:54
 * @description
 */
public class MyArray {
    List lines;
    List teachers;

    public List getLines() {
        return lines;
    }

    public void setLines(List lines) {
        this.lines = lines;
    }

    public List getTeachers() {
        return teachers;
    }

    public void setTeachers(List teachers) {
        this.teachers = teachers;
    }
    
}

spring xml configuration file:


    
    


    
    



    
        
            第一行
            第二行
        
    
    
        
            
            
        
    

test:

lassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
MyArray myarray = (MyArray) context.getBean("array1");
List lines = myarray.getLines();
List teachers = myarray.getTeachers();
for (String line : lines) {
    System.out.println(line);
}
for (Teacher teacher : teachers) {
    System.out.println(teacher.toString());
}

Automated assembly

And Mybatis, like, spring also have convention over configuration, as long as comply with the contract, spring will automatically help us to complete the property value above the injection operation.

We can automatically assembled by attribute name, attribute type or constructor

Automatic assembly is only applicable to the type of object (a reference type, ref)

byName>byType>constructor

Our previous Student Teacher class contains a class attribute



...



Large projects generally do not recommend apply automatic assembly, it will affect the readability

Reference links: Spring automatic assembly

scope of the bean

Scope

description

In the spring IoC container exists only one example Bean, Bean manner in the presence of a single embodiment, the default value

Each time the call Bean, returns a new instance of the container, i.e., each call to the getBean (), equivalent to the implementation newXxxBean ()

Each HTTP request will create a new Bean, that scope applies only to the environment WebApplicationContext

Share a same HTTP Session Bean, different Session using different Bean, applies only to the environment WebApplicationContext

Portlet applications for the general environment, the use of domain applies only to the environment WebApplicationContext

singleton
prototype
request
session
global-session

Reference links: Spring Bean scopes

Annotations way

Use @ Controller, @ Service, @ Repository, @ Component identification and other categories annotation (Bean), arranged after the context xml: component-scan automatic scan labels

annotation

range

Common

Controller class label for layer (a specific the Servlet)

Dao layer label for class

Services class used to label layer

@Component
@Controller
@Repository
@Service

General Notes recommended after refinement, i.e. the last three, the same methods are used, a simple reference to the following example


@Component("student1")
public class Student{
    @Value("001")
    private String sno;
}



    

Use the time to add the following code in the configuration file of spring



    
    
    

Note that the configuration file to add the attribute xmlns: context = "http://www.springframework.org/schema/context

xsi: schemaLocation attributes which have a http://www.springframework.org/schema/context/spring-context.xsd

Otherwise, the error will be "wildcard match is very comprehensive, but could not find the elements 'context: component-scan' statement."

Use words as before

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Student student = (Student) context.getBean("student1");

Leave a Reply