The summary of Sping

Spring is a lightweight Inversion of Control (IoC) and AOP oriented container framework.

The characteristics of the Spring

1.Spring is a free open source framework (container) 2.Spring is a lightweight, non-invasive framework 3. Inversion of control (IOC) Aspect oriented programming (AOP) core 4. Support transaction processing, integration of the framework

Using the Spring

We only need to import the Spring-WebMVC framework package for our Maven project, and Maven will automatically import the other dependencies for us

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> < version > 5.2.8. RELEASE < / version > < / dependency >Copy the code

Sping’s seven core modules

Core Container (Spring Core)

The core container provides the basic functionality of the Spring framework. Spring organizes and manages components and their relationships in Java applications as beans. Spring uses the BeanFactory, which is an implementation of the factory pattern, to generate and manage beans. The BeanFactory uses an inversion of Control (IoC) pattern to separate the application’s configuration and dependency specifications from the actual application code.

Application Context

A Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, E-mail, internationalization, validation, and scheduling capabilities.

Spring AOP

Spring AOP modules integrate aspect-oriented programming capabilities directly into the Spring framework through configuration management features. So, you can easily make any object managed by the Spring framework AOP enabled. The Spring AOP module provides transaction management services for objects in Spring-based applications. Using Spring AOP, you can integrate declarative transaction management into your application without relying on EJB components.

JDBC and DAO modules (Spring DAO)

The JDBC, DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error information thrown by different database vendors. Exception hierarchies simplify error handling and greatly reduce the amount of code you need to write, such as opening and closing links.

Object Entity Mapping (Spring ORM)

The Spring framework inserts several ORM frameworks to provide relational tools for ORM objects, including Hibernate, JDO, and IBatis SQL Map, all of which follow Spring’s generic transaction and DAO exception hierarchy.

Web Module (Spring Web)

The Web context module is built on top of the application context module and provides the context for Web-based applications. So the Spring framework supports integration with Struts, and the Web module also simplifies handling multi-part requests and binding request parameters to domain objects.

MVC Module (Spring Web MVC)

The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework becomes highly configurable through the policy interface. MVC contains a large number of view technologies, including JSP, POI and so on. The model is composed of Javabeans and stored in M, while the view is a street, responsible for the realization of the model, and the controller represents the logical code, which is done by C. The features of the Spring framework can be used in any J2EE server, and most of the features can be used in an unmanaged environment. Spring’s core point is to support reusable business and data access objects that are not tied to specific J2EE services, and such objects can undoubtedly be reused across different J2EE environments, standalone applications, and test environments.

Sping’s three core ideas

DI(dependency injection) : When the background needs an object, the Spring container will inject an empty object into the background in the form of a bean. New functionality is dynamically added horizontally throughout the system without changing the coding of the original business process. So how to understand horizontal expansion? In WEB project development, we usually abide by the principle of three layers: including the control layer (Controller) -> business layer (Service) -> data layer (DAO), then from this structure down is vertical, and a specific layer of it is what we call horizontal. (AOP is complementary to OOP)

IOC Create object

To create Spring’s XML configuration applicationContext.xml, refer to the Sping official documentation

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="..." class="..."> <! -- collaborators and configurationfor this bean go here -->
    </bean>

    <bean id="..." class="..."> <! -- collaborators and configurationforthis bean go here --> </bean> <! -- more bean definitions go here --> </beans>Copy the code

Hello.java

package com.zx.hello; /** * @author Tim * @date 2020/7/22 22:43 * @version 1.0 */ public class Hello {private String Hello; public StringgetHello() {
        returnhello; } / /setWhat is the key here (bysetPublic void () without Set ()setHello(String hello) {
        this.hello = hello;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "hello='" + hello + '\''+'}'; }}Copy the code

Previously create object:

Hello hello = new Hello();
Copy the code

Now in the Sping configuration file (as long as the Hello class must exist) : id = variable name — Hello class = new Hello(); Bean = object property = object property value

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <! Use Spring to create objects called beans --> <! The ID attribute is a string that identifies a single bean definition. The class attribute defines the type of the Bean and uses the fully qualified class name. The value of the ID attribute refers to the collaboration object. The XML used to reference the collaboration object is not shown in this example --> <! -- bean = object Hello Hello = new Hello(); Object property with id= variable name class = new is equivalent to assigning a value to an attribute in the object --> <bean ID ="hello" class="com.zx.hello.Hello"> <! -- Set the value for the object property --> <property name="hello" value="spring"></property> <! -- collaborators and configurationforthis bean go here --> <! --ref refers to objects created in the Spring container --> <! --<property name="xx" ref="conversionService"></property>-->
	    </bean>
   </beans>
Copy the code

The object can then be invoked in the Java implementation class (created as soon as the sping container loads the object)

/ / get the Spring objects up and down (for the Spring container) ApplicationContext ac = new ClassPathXmlApplicationContext ("beans.xml"); // At this point our object is managed in Spring, we just need to get it. Hello hello = (Hello) ac.getBean("hello");
Hello hello = ac.getBean("hello",Hello.class);
Copy the code

IOC how objects are created

Create an object with a no-parameter construct (default) Create an object with a parameter construct (as follows)Copy the code
    <bean id="user1" class="com.zx.user.Users"> <! --> <constructor-arg index="0" value="Bill"></constructor-arg> </bean> <! It is not recommended to use the went type when there are multiple same types --> <bean id="user2" class="com.zx.user.Users">
        <constructor-arg type="java.lang.String" value="Fifty"></constructor-arg> </bean> <! -- Directly through the parameter name --> <bean id="user3" class="com.zx.user.Users">
        <constructor-arg name="name" value="Dong Bin"></constructor-arg>
    </bean>
Copy the code

DI(Dependency injection)

Dependencies: Bean object creation depends on container injection: all property values in the bean object are injected by the container. Constructor injection (front)

2. Set injection

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="home" class="com.zx.Home">
        <property name="home" value="Xuancheng, Anhui province"></property>
    </bean>
    <bean id="student" class="com.zx.Student">
        <property name="name" value="Jay huang"></property>
        <property name="home" ref="home"/>
        <property name="books"> <array> <value> <value> Water Margin </value> <value> <value> Romance of The Three Kingdoms </value> <value> <value> a Dream of red Mansions </value> </array> </property> <property name="hobbys"> <list> <value> Multiplayer </value> <value> basketball </value> </list> </property> <property name="cards">
            <map>
                <entry key="Identity card" value="111111111111"></entry>
                <entry key="Bank card" value="23456s"></entry>
            </map>
        </property>

        <property name="games">
            <set> <value> King of Glory </value> <value> Stimulate the battlefield </value> </set>
        </property>
        <property name="info">
            <props>
                <prop key="Student id">16014420048</prop>
                <prop key="Name"> rhubarb </props> </property> <property name="wrok">
            <null></null>
        </property>
    </bean>
</beans>
Copy the code

3. Other injections

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <! Add a parameterless constructor to the USER classsetInject property --> <bean id="user1" class="com.obj.User" p:name="Zhang" p:age="18" scope="prototype"></bean> <! <bean id= > <bean id= > <bean id= > <bean id= > <bean id= > <bean id= > <bean id= > <bean id="user2" class="com.obj.User" c:name="Bill" c:age="20"></bean> <! --p and c namespaces can not be used directly, import XML constraints --> <! Use request, session, application --> </beans>Copy the code
The p and C namespaces cannot be used directly, and the XML constraint <! Use request, session, application in Web developmentCopy the code

The essence of the IOC

IOC (Inversion of Control), he is a design idea! The essence of IOC is that the way in which dependent objects are acquired is reversed, so that the program no longer manages object creation, so that the coupling of the program is greatly reduced and object creation can be handed over to a third party. Inversion of control is a way of describing (XML configuration files, annotations) objects generated or retrieved by a third party. In Sping, the IOC container implements inversion of control through DI(dependency injection).

Supplementary (auto assembly)

Bean autowiring is a way that Spring satisfies Bean dependencies, and Sping automatically finds and assembs the Bean’s ownership in the context. There are three assembly methods in Spring: 1. display configuration in XML 2. display configuration 3 in Java. Implicit autowiring (***)

A:

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="cat" class="com.zx.Cat">
        <property name="name" value="Because"/>
    </bean>

    <bean id="dog" class="com.zx.Dog">
        <constructor-arg name="name" value="Doug"/>
    </bean>

    <bean id="people" class="com.zx.People">
        <property name="name" value="Rhubarb"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/> </bean> <! -- Automatic assembly --> <! ByName will automatically find and own objects in the containersetThe value after the method corresponds to the bean ID --> <bean ID ="people1" class="com.zx.People" autowire="byName">
        <property name="name" value="The fly"/> </bean> <! ByType automatically searches the container for the bean ID of its object type --> <bean ID ="people2" class="com.zx.People" autowire="byType">
        <property name="name" value="Miss Dong"/>
    </bean>

</beans>
Copy the code
import com.zx.People; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Tim * @date 2020/7/23 17:12 * @version 1.0 */ public class Test6 {public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        People people = ac.getBean("people",People.class);
        people.getCat().show();
        people.getDog().show();
        System.out.println("This man is called."+people.getName());


        People people1 = ac.getBean("people1",People.class);
        people1.getCat().show();
        people1.getDog().show();
        System.out.println("This man is called."+people1.getName());


        People people2 = ac.getBean("people2",People.class);
        people2.getCat().show();
        people2.getDog().show();
        System.out.println("This man is called."+people2.getName()); }}Copy the code

Second,

JavaConfig is a subproject of Spring and became a core feature after Spring4

@Configuration represents a Configuration class, just like our bean.xml. @ComponentScan("com.zx"Registering a Bean is the Bean label, the method name is the ID, and the return value is the class attributeCopy the code
package com.config; import com.zx.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * @author Tim * @date 2020/7/24 17:51 * @version 1.0 */ @configuration / Because it's a @Component @ComponentScan("com.zx"Public class UserConfig {@bean // Register a Bean as the Bean tag, the method name is the id, the return value is the class attribute public UsergetUser() {returnnew User(); }}Copy the code
package com.zx; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @author Tim * @date 2020/7/24 17:48 * @version 1.0 */ @component public class User {private String name; public StringgetName() {
        return name;
    }
    @Value("Zhang")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\''+'}'; }}Copy the code
import com.config.UserConfig; import com.zx.User; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @author Tim * @date 2020/7/24 17:57 * @version 1.0 */ public class Test9 {public static void main(String[] args) {/ / such as configuration method is used to do completely, through AnnotationConfigApplicationContext context to get the container, Through the configuration class loading ApplicationContext ac = new AnnotationConfigApplicationContext class object (UserConfig. Class); User user = ac.getBean("getUser",User.class); System.out.println(user.getName()); }}Copy the code

Methods three,

Annotation implementation autowiring uses annotations to enable annotation support

 <context:annotation-config/>
Copy the code
1.@Autowired can be used directly on properties or on Set methods. This annotation is implemented using reflection and can be injected without the SET method (provided that the attributes you want to autoassemble exist in the IOC container (Spring) and conform to byType). If the autoassemble environment is more complex, add @qualifier (value =)"dog111") with @autoWired to get a unique value. @Autowired(required =false)//required = falseAllow null 2.@Resource in the container (is a JDK annotation. Not Sping) 3.@Nullable mark it as @nullable if NULL can be passed, or @nonNULL if not. So these comments will give us a little bit of a warning when we're doing code operations that aren't securely rigorous. @ the Resource and the @autowired are doing bean injection is used when, in fact the @ the Resource is not Spring annotations, it's bag is javax.mail annotation. The Resource, but Spring supports the annotation of injection. Both can be written on fields and setter methods. If you write both on the field, then you don't need to write setter methods anymore. 2, the difference between (1) the @autowired @autowired annotation for the Spring, you need to import the package org. Springframework. Beans. Factory. The annotation. Autowired; Injection by byType only. The @autowired annotation assembles dependent objects byType (byType). By default, it requires that the dependent object must exist. If null values are allowed, its required attribute can be set to false. If we want to use assembly byName (byName), we can use it in conjunction with the @qualifier annotation. (2) @ Resource @ Resource default in accordance with the ByName automatic injection, provided by J2EE, you need to import the package javax.mail. The annotation. The Resource. The @resource has two important attributes: name andtype, and Spring resolves the name attribute of the @Resource annotation to the bean name, whiletypeProperty resolves the type of the bean. So, if the name attribute is used, the automatic injection policy of byName is used, while the name attribute is usedtypeAttribute uses the byType automatic injection strategy. If neither name is specified nor name is specifiedtypeProperty, in which case the byName auto-injection policy is used through reflection.Copy the code

Spring annotation development To use annotation development after Spring 4, you must ensure that the AOP framework package 1 is imported. Use annotations to add annotation support! (Mainly the annotation driver for opening the program)

  <context:annotation-config/>
Copy the code
2. The scanning mechanism specifies the package to scan, and the annotations under that package (Spring-specific annotations) <context: Component-scan base-package="com"/> Annotation (bean) 1.@Component (Component) @component is equivalent to <bean id="user" class="com.entity.User"></bean> 2.@Value() Spring annotations inject property values using @value ("Rhubarb") equals <property name="xxx" value="xxx"></property> 3.@Component derived annotation (1) @repository (Repository persistence layer) (2) @service (business layer) (3) @controller (Controller layer) Both represent registering a class in Spring and assembling Bean 4. Scope annotation @scope ("singleton")
Copy the code
package com.bean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import javax.annotation.Resource; /** * @author Tim * @date 2020/7/24 14:37 * @version 1.0 */ public class Peope {@resource private Cat Cat; @Autowired(required =false)//required = falseNull @qualifier (value =) is allowed in containers"dog111")
    private Dog dog;

    private String name;

    public void show(){
        cat.Show();
        dog.show();
        System.out.println("You are all my pets."); }}Copy the code
package com.bean; /** * @author Tim * @date 2020/7/24 14:30 * @version 1.0 */ public class Cat {private String name; public voidShow(){
        System.out.println("Hello, I'm Kitty."); } } package com.bean; /** * @author Tim * @date 2020/7/24 14:36 * @version 1.0 */ public class Dog {private String name; public voidshow(){
        System.out.println("I am a dog."); }}Copy the code
<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="cat" class="com.bean.Cat"></bean>
    <bean id="dog11" class="com.bean.Dog"></bean>
    <bean id="dog111" class="com.bean.Dog"></bean>

    <bean id="people" class="com.bean.Peope"></bean> <! <context:annotation-config/> </beans>Copy the code

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!