Do you really know what spring is? Spring Quick Start Guide

Time:2022-1-11

1.spring

Spring framework can be said to be the most successful framework in the Java world. In enterprise practical applications, most enterprise architectures are based on spring framework. Its success comes from ideas, not technology. Its core ideas are IOC (control inversion) and AOP (aspect oriented programming). IOC is the foundation of spring, and AOP is its important function. The most typical is the use of database transactions.

Spring’s most fundamental mission is to solve the complexity of enterprise application development, that is, simplify java development.

1.1. advantage

  1. Convenient decoupling and simplified development

    Spring is a big factory, which can manage the creation of all objects and the maintenance of dependencies.

  2. AOP programming support

    Spring provides aspect oriented programming, which can easily realize the functions of permission interception, operation monitoring and so on.

  3. Declarative transaction support

    Transaction management can be completed through configuration without manual programming.

  4. Facilitate program testing

    Spring supports junit4. You can easily test spring programs through annotations.

  5. Convenient integration of various excellent frameworks

    Spring does not exclude various excellent open source frameworks. It provides direct support for various excellent frameworks (such as struts, hibernate, mybatis, etc.).

  6. Reduce the difficulty of using Java EE API

    Spring provides encapsulation for some APIs (JDBC, JavaMail, remote call, etc.) that are very difficult to use in Java EE development, which greatly reduces the difficulty of applying these APIs.

1.2. shortcoming

  1. Spring is obviously a very lightweight framework, but it feels large and comprehensive
  2. Spring relies on reflection, which affects performance
  3. It takes a long time to get started with spring

1.3. Composition structure diagram of spring framework

Spring has about 20 modules in total, consisting of more than 1300 different files. These components are integrated into six modules: core container, AOP (aspect oriented programming), instrumentation, data access / integration, web, messaging and test. The following is the module structure diagram of spring 5:

Do you really know what spring is? Spring Quick Start Guide

Each module (or component) that makes up the spring framework can exist alone or be implemented jointly with one or more other modules. The functions of each module are as follows:

1.3.1. Core container

Spring’s core container is the basis for the establishment of other modules, including spring core, spring beans, spring context, spring context support and spring expression (spring expression language).

Spring core module: provides the basic components of the framework, including inversion of control (IOC) and dependency injection (DI).

Spring beans module: provides beanfactory, which is a classic implementation of the factory pattern. Spring calls the management object bean.

Spring context module: Based on the core and beans modules, it provides a framework object access method, which is the medium to access any object defined and configured. The ApplicationContext interface is the focus of the context module.

Spring context support module: support the integration of third-party libraries into spring application context, especially for cache (ehcache, jcache) and task scheduling (commonj, quartz).

Spring expression module: provides a powerful expression language to support runtime query and operation object graph. This is for JSP 2 1. Extension of unified expression language (EL) specified in the specification. The language supports setting and obtaining property values, property assignments, method calls, accessing the contents of arrays, collections and indexers, logical and arithmetic operations, variable naming, and retrieving objects by name from spring’s IOC container. It also supports list projection, selection, and common list aggregation.

1.3.2. AOP and device support

It is composed of three modules: Spring AOP, spring aspects and spring instrument.

Spring AOP module: is another core module of spring, which provides an aspect oriented programming implementation that meets the requirements of AOP. As one of the most influential programming ideas for programmers after OOP (object-oriented programming), AOP has greatly opened up people’s thinking about programming. In spring, based on dynamic proxy technology, it allows to define method interceptors and pointcuts, and separate the code according to function, so as to decouple cleanly.

Spring aspects module: provides integration with AspectJ, a powerful and mature AOP framework.

Spring instrument module: is a support module of AOP, which provides class instrumentation support and class loader implementation, and can be used in specific application servers. The main function is to generate a proxy class when the JVM is enabled. Programmers can modify the bytes of the class at runtime through the proxy class, so as to change the function of a class and realize the function of AOP.

1.3.3. Data access and integration

It consists of five modules: Spring JDBC, spring ORM, spring oxm, spring JMS and spring TX.

Spring JDBC module: provides a JDBC abstraction layer, eliminates cumbersome JDBC coding and database vendor specific error code parsing, and is used to simplify JDBC. It mainly provides JDBC template mode, relational database objectification mode, simplejdbc mode and transaction management to simplify JDBC programming. The main implementation classes are jdbctemplate, simplejdbctemplate and namedparameterjdbctemplate.

Spring ORM module: it is an ORM framework support module, which mainly integrates hibernate, Java persistence API (JPA) and Java data objects (JDO) for resource management, data access object (DAO) implementation and transaction strategy.

Spring oxm module: it mainly provides an abstraction layer to support oxm (oxm is the abbreviation of object to XML Mapping, which is an O / m-mapper that maps Java objects to XML data or XML data to Java objects), such as JAXB, castor, xmlbeans, jibx and xStream.

Spring JMS module (Java messaging service): refers to a Java messaging service that contains functions for producing and using messages. From spring 4 After 1, integration with spring messaging module is provided.

Spring TX module: transaction module, which supports programming and declarative transaction management for implementing special interfaces and all POJO (ordinary Java object) classes.

1.3.4.Web

It consists of five modules: spring websocket, spring webmvc, spring web, portlet and spring weblux.

Spring websocket module:Spring4. 0, which implements duplex asynchronous communication protocol, websocket and socketjs, and provides socket communication and web push functions.

Spring webmvc module: also known as the web servlet module, it contains spring MVC and rest Web Services implementations for web applications. The spring MVC framework provides a clear separation between domain model code and web forms, and integrates with all other functions of the spring framework.

Spring web module: provides basic web development integration functions, including initializing an IOC container and web application context with servlet listener, automatically loading classes of webapplicationcontext feature, struts integration class, file upload support class, filter class and a large number of auxiliary tool classes.

Portlet module: realize the aggregation of web module functions, similar to the functions of servlet module, and provide MVC implementation in portlet environment.

Spring weblux module: is a new non blocking functional reactive web framework, which can be used to establish asynchronous, non blocking, event driven services, and has very good scalability.

1.3.5. Message (messaging)

Spring messaging module.

spring-messagingIs a newly added module from spring 4, which provides support for messaging architecture and protocols.

1.3.6.Test

Spring test module.

Spring test moduleIt mainly provides support for testing. It supports unit testing and integration testing of spring components using JUnit or TestNG.

2. Spring core IOC

IOC inversion of control is not a technology, but a design idea. In java development, IOC means that the object you designed is controlled by the container, rather than the traditional direct control inside your object. Just don’t instantiate. Inject first.

Who controls who, what:In traditional Java se programming, we directly create objects inside objects through new, which is the program’s initiative to create dependent objects; IOC has a special container to create these objectsIOC containerTo control the creation of objects; Who controls who? CertainlyThe IOC container controls the object; Control what? That’s itIt mainly controls the acquisition of external resources

Why and in what waysIf there is inversion, there is forward rotation. In traditional applications, we actively control ourselves in the object to directly obtain the dependent object, that is, forward rotation; The container helps create and inject dependent objects; Why reverse? Because the container helps us find and inject dependent objects, the objects only passively accept dependent objects, so it is inversion; What aspects are reversed? The acquisition of dependent objects is reversed.

PS: inversion of control is the goal and dependency injection is the means.

2.1. IOC container

Do you really know what spring is? Spring Quick Start Guide

IOC container is the core of spring, which can also be called spring container. Spring manages the instantiation and initialization of objects through the IOC container, as well as the whole life cycle of objects from creation to destruction.

All objects used in spring are managed by the IOC container, so we don’t need to manually use the new operator to create objects. The object managed by the IOC container is called spring bean. Spring bean is a Java object, which is no different from the object created using the new operator.

Spring obtains which objects need to be instantiated by reading the information in XML or Java annotations.

Spring provides two different types of IOC containers, namely beanfactory and ApplicationContext containers

2.1. Beanfactory container

Beanfactory is the simplest container, which is provided by org springframework. beans. factory. Beanfactory interface definition adopts lazy load, so the container starts relatively quickly. Beanfactory provides the most basic functions of containers.

In order to be compatible with spring integrated third-party frameworks (such as beanfactoryaware, initializingbean and disposablebean), the interface is still retained.

In short, beanfactory is a factory that manages beans. It is mainly responsible for initializing various beans and calling their life cycle methods.

Beanfactory interface has multiple implementation classes, the most common of which is org springframework. beans. factory. xml. XmlBeanFactory。 To use beanfactory, you need to create an instance of xmlbeanfactory class and pass the resource object through the constructor of xmlbeanfactory class. As shown below.

Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);  

2.1.2. ApplicationContext container

ApplicationContext inherits the beanfactory interface, which is provided by org springframework. context. The ApplicationContext interface defines that the object is loaded when the container is started. ApplicationContext adds many enterprise level functions on the basis of beanfactory, such as AOP, internationalization, event support, etc.

The ApplicationContext interface has two common implementation classes, as follows.

2.1.2.1.ClassPathXmlApplicationContext

This class looks for the specified XML configuration file from the classpath classpath and completes the instantiation of ApplicationContext, as shown below.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(String configLocation);

In the above code, the configlocation parameter is used to specify the name and location of the spring configuration file, such as beans xml。

2.1.2.2.FileSystemXmlApplicationContext

This class looks for the specified XML configuration file from the specified file system path and completes the instantiation of ApplicationContext, as shown below.

ApplicationContext applicationContext = new FileSystemXmlApplicationContext(String configLocation);

The difference between it and classpathxmlapplicationcontext is that when reading the configuration file of spring, filesystemxmlapplicationcontext does not read the configuration file from the classpath, but specifies the location of the configuration file through parameters. That is, filesystemxmlapplicationcontext can obtain resources outside the classpath, such as “F: / workspaces / beans. XML”.

2.1.2.3.AnnotationConfigApplicationContext

Creating containers with annotations for reading

Generally, in Java projects, the classpathxmlapplicationcontext class will be used to instantiate the ApplicationContext container, while in web projects, the instantiation of the ApplicationContext container will be completed by the web server. The ApplicationContext container instantiated by the web server is usually implemented based on the contextloaderlistener, which only needs to be implemented on the web Add the following code to XML:

<!-- Specify the location of spring configuration files. When there are multiple configuration files, they are separated by commas -- >
<context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- Spring will load the ApplicationContext under the spring directory XML file -- >
    <param-value>
        classpath:spring/applicationContext.xml
    </param-value>
</context-param>
<!-- Specifies to start the spring container as contextloaderlistener -- >
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

It should be noted that beanfactory and ApplicationContext load beans through XML configuration files.

The main difference between the two is that if an attribute of a bean is not injected, after loading with beanfactory, an exception will be thrown when calling the getBean () method for the first time, while ApplicationContext will conduct self-test during initialization, which is conducive to checking whether the dependent attribute is injected.

Therefore, in actual development, ApplicationContext is usually used. Beanfactory is considered only when there are few system resources.

2.2. Using IOC containers

2.2.1.beans.xml

<?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>
        < property name = "name" value = "Wang Yanling" / >
    </bean>
</beans>

2.2.2.pojo.User

public class User { 
    private String name; 
    public User() {
        System. out. Println ("user parameterless construction method");
    } 
    public void setName(String name) {
        this.name = name;
    } 
    public void show(){
        System.out.println("name="+ name );
    }
}

2.2.2.test

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //When the getBean is executed, the user has been created and constructed without parameters
    User user = (User) context.getBean("user");
    //Call the method of the object
    user.show();
}

2.3.bean

2.3.1. definition

The object managed by the spring IOC container is called a bean, which is created according to the information in the spring configuration file. The spring IOC container can be regarded as a large factory. Beans are equivalent to factory products. If you want this large factory to produce and manage beans, you need to tell the container which beans are needed and how to assemble beans.

The spring configuration file supports two formats: XML file format and properties file format.

  • The properties configuration file mainly exists in the form of key value pairs. It can only assign values and cannot perform other operations. It is suitable for simple property configuration.

  • The XML configuration file is a tree structure, which is more flexible than the properties file. The structure of XML configuration file is clear, but the content is cumbersome, which is suitable for large and complex projects.

Typically, spring’s configuration files are in XML format. The root element of the XML configuration file is < beans style = “margin: 0px; padding: 0px;” >, This element contains multiple child elements < bean style = “margin: 0px; padding: 0px;” >. Each < bean style = “margin: 0px; padding: 0px;” > The element defines a bean and describes how the bean is assembled into the spring container</ bean></bean></beans>

2.3.2. establish

2.3.2.1 default mode

No parameter

<!--  1\.  Default constructor. If there is no default constructor in the class, the object cannot be created; If there are only ID and class in the bean tag, the constructor is used by default to create objects -- >
<bean/>

Have reference

<!--  The first one is set according to the index parameter subscript -- >
<bean>
    <!--  Index refers to the construction method, and the subscript starts from 0 -- >
    <constructor-arg index="0" value="wyl"/>
</bean>

<!--  The second is to set -- > according to the parameter name
<bean>
    <!--  Name refers to the parameter name -- >
    <constructor-arg name="name" value="wyl"/>
</bean>
<!--  The third method is set according to the parameter type -- >
<bean>
    <constructor-arg type="java.lang.String" value="wyl"/>
</bean>

2.3.2.2 methods in plant class

<!--  2\.  Create objects using methods in the factory; There is a method in the factory to create an object. First create a factory object, point to the factory through the factory bean, and use the factory method to obtain the object -- >
<bean/>
<bean factory-bean="beanFactory" factory-method="getUserService"/>

2.3.2.3 static methods in static plants

<!--  3\.  Create objects using static methods in a static factory -- >
<bean factory-method="getUserService"/>

2.3.2. to configure

2.3.2.1. alias

<!--   Alias: if an alias is added, we can also use the alias to get this object -- >
<alias name="User" alias="u1"></alias>

2.3.2.2. Bean alias

<!--
  Bean tag common properties:

ID attribute: name. The ID attribute value name can be named arbitrarily and cannot contain special symbols
Class attribute: the full path of the class where the object is created
Name attribute: the function is the same as the ID attribute, but the name attribute value can contain special symbols
Scope property
Singleton: default value, single instance
Prototype: multiple cases
Request: create an object and put the object in the request field
Session: create an object and put the object into the session domain
Globalsession: create an object and put the object in the globalsession
  -->
<bean scope="singleton" name="u2 u21,u22;u23">
    <property name="name" value="123"/>
</bean>

2.3.2.2.import

Team cooperation is achieved through import

<import resource="beans.xml"/>

It can integrate different configuration XML files developed by multiple people into ApplicationContext XML file, and can be properly de duplicated.

2.3.3. Scope

<bean scope="singleton"/>

When initializing a bean instance, the spring container will also specify the scope of the instance. Spring 5 supports the following six scopes.

singleton

Default, singleton mode, which means that there is only one bean instance in the spring container, and the bean exists as a singleton.

prototype

The prototype pattern indicates that each time a bean is obtained through the spring container, the container will create a bean instance.

request

For each HTTP request, the container creates a bean instance. This scope is only valid within the current HTTP request.

session

The same HTTP session shares a bean instance, and different sessions use different bean instances. This scope is only valid within the current HTTP session.

application

The same web application shares a bean instance, and the scope is valid in the current ServletContext.
Similar to singleton, the difference is that singleton means that there is only one bean instance in each IOC container, while there may be multiple IOC containers in the same web application, but a web application will only have one ServletContext. It can also be said that application is the real singleton mode in web applications.

websocket

The scope of websocket is websocket, that is, it is valid in the whole websocket
Request, session, application, websocket and global session scopes can only be used in the web environment. If you use classpathxmlapplicationcontext to load the bean of any of these scopes, the following exception will be thrown.

2.3.4. life cycle

Do you really know what spring is? Spring Quick Start Guide

Bean life cycle
  1. Spring starts, finds and loads the beans that need to be managed by spring, and instantiates the beans.

  2. Use dependency injection to complete the configuration injection of all attribute values in the bean.

  3. If the bean implements the beannameaware interface, spring calls the bean’s setbeanname () method to pass in the ID value of the current bean.

  4. If the bean implements the beanfactoryaware interface, spring calls the setbeanfactory () method to pass in the reference of the current factory instance.

  5. If the bean implements the applicationcontextaware interface, spring calls the setapplicationcontext () method to pass in the reference of the current ApplicationContext instance.

  6. If the bean implements the [beanpostprocessor] interface, spring calls the pre initialization method postprocessbeforeinitialization() of the interface to process the bean. This is very important here. Spring’s AOP is implemented using it.

  7. If the bean implements the initializingbean interface, spring will call the afterpropertieset () method.

  8. If an initialization method is specified in the configuration file through the init method attribute, the initialization method is called.

  9. If [beanpostprocessor] is associated with a bean, spring will call the initialization method postprocessafterinitialization() of the interface. At this point, the bean can already be used by the application system.

  10. If in < bean style = “margin: 0px; padding: 0px;” > If the scope of the bean is specified as singleton in, put the bean into the cache pool of spring IOC to trigger spring’s life cycle management of the bean; If in < bean style = “margin: 0px; padding: 0px;” > If the scope of the bean is specified as prototype in, the bean will be handed over to the caller, who will manage the life cycle of the bean, and spring will no longer manage the bean</ bean></bean>

  11. If the bean implements the disposablebean interface, spring will call the destroy () method to destroy the bean; If the destruction method of the bean is specified in the configuration file through the destruction method attribute, spring will call this method to destroy the bean.

2.3.4.1. Single case

public class UserBean {
    private String name;  

    public UserBean(){  
        System. out. Println ("userbean () constructor");  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        System.out.println("setName()");  
        this.name = name;  
    }  
    public void init(){  
        System.out.println("this is init of UserBean");  
    }  

    public void destory(){  
        System.out.println("this is destory of UserBean " + this);  
    }  
}
<bean scope="singleton" 
            init-method="init" destroy-method="destory" lazy-init="true"/>

When scope = “Singleton”, that is, by default, it will be instantiated when the container is started (that is, when the container is instantiated). However, we can specify the lazy init = “true” of the bean node to delay the initialization of the bean. At this time, the bean will be initialized only when the bean is obtained for the first time, that is, when the bean is requested for the first time

If you want to apply deferred initialization to all default singleton beans, you can set the default lazy init attribute to true on the root node beans, as shown below:

<beans default-lazy-init="true">

public class LifeTest {
    @Test 
    public void test() {
        AbstractApplicationContext container = 
        new ClassPathXmlApplicationContext("user.xml");
        UserBean user = (UserBean)container.getBean("user_singleton");
        System.out.println(user);
        container.close();
    }
}

Userbean() constructor
this is init of UserBean
[email protected]
……
this is destory of [email protected]

By default, spring creates objects when it reads XML files. When creating an object, call the constructor first[UserBean()And then invoke the method specified in the init-method attribute value. When the object is destroyed, the method specified in the destroy method attribute value will be called

2.3.4.2. Non singleton managed objects

When scope = “prototype”, the container will also delay initializing the bean. When spring reads the XML file, it will not create the object immediately, but will initialize the bean the first time it is requested (such as when calling the getBean method).

At the first request for every prototype bean, the Spring container calls its constructor to create the object and then calls the method specified in the init-method attribute value. When the object is destroyed, the spring container will not call any methods for us, because it is a non singleton. There are many objects of this type. Once the spring container gives you this object, it will no longer manage this object.

<bean scope="prototype" init-method="init" destroy-method="destroy"/>

public class UserTest {
    @Test 
    public void test() {
        AbstractApplicationContext container = new ClassPathXmlApplicationContext("User.xml");
        UserBean User1 = (UserBean)container.getBean("User_singleton");
        System.out.println(User1);

        UserBean User2 = (UserBean)container.getBean("User_prototype");
        System.out.println(User2);
        container.close();
    }
}

result

Userbean() constructor
this is init of UserBean
[email protected]
Lifebean() constructor
this is init of UserBean
[email protected]
……
this is destory of lifeBean [email protected]

2.4. Di (dependency injection)

Dependency injection. In the process of decoupling, we hand over the creation of objects to the spring container for management. When we need to use objects of other classes provided by spring, we just need to declare them in the configuration file. Class a uses class B to generate dependencies. Spring solves the dependencies by dependency injection (DI)

2.4.1. Constructor Injection

private String name;
private Integer age;
private Date birthday;
//Constructor
public UserServiceImpl(String name, Integer age, Date birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
<!--  Name: auxiliary by field name; Index: field index, assigning values to the fields; Type: Specifies the type of injected value, which is also the type of one or some fields in the constructor; -- >
<!--  Value: the value to be injected, basic type and string; Ref: inject other types of data, pointing to external bean objects; This external bean needs to exist in the spring container -- >
<bean>
    < constructor Arg name = "name" value = "Zhang San" / >
    <constructor-arg name="age" value="12"/>
    <constructor-arg name="birthday" ref="date"/>
</bean>
<!--  Create date object -- >
<bean/>

2.4.2. Set mode injection

private String name;
private Integer age;
private Date birthday;
public void setName(String name) {
    this.name = name;
}

public void setAge(Integer age) {
    this.age = age;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

<bean>
    < property name = "name" value = "Li Si" / >
    <property name="age" value="12"/>
    <property name="birthday" ref="date"/>
</bean>
<!--  Create date object -- >
<bean/>

2.4.3. Object type injection

<!--  Injection object type attribute -- >
<!--  1 configure service and Dao objects -- >
<bean></bean>
<bean>
    <!--  Inject Dao objects -- >
    <property name="userDao" ref="userDao"></property>
</bean>

2.4.4. Complex type injection

<!--  Inject complex type attribute values -- >
  <bean>
    <!--  Array -- >
    <property name="arrs">
       <list>
         < value > Xiao Wang < / value >
         < value > pony < / value >
         < value > Xiao song < / value >
       </list>
    </property>

    <!-- list -->
    <property name="list">
       <list>
         < value > Xiao Ao < / value >
         < value > Xiao Jin < / value >
         < value > Xiao Pu < / value >
       </list>      
    </property>

    <!-- map -->
    <property name="map">
       <map>
         <entry key="aa" value="lucy"></entry>
         <entry key="bb" value="mary"></entry>
         <entry key="cc" value="tom"></entry>
       </map>
    </property>

    <!-- properties -->
    <property name="properties">
       <props>
         <prop key="driverclass">com.mysql.jdbc.Driver</prop>
         <prop key="username">root</prop>
       </props>
    </property>
  </bean>
<!--set-->
<property name="set">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>WOW</value>
            </set>
</property>
<!--null-->
<property name="marne">
            <null/>
</property>

2.4.5. Expansion mode injection

<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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

P named injection property

<!--  P namespace injection, you can directly inject the value of the property: Property -- >
< bean P: name = "Lao Qin" P: age = "18" / >

C namespace injection constructor

<!--  C namespace injection through constructor: construct args -- >
< bean C: age = "18" C: name = "Lao Li" / >

Note: P naming and C naming cannot be used directly. You need to import XML constraints

2.5. automatic assembly

Automatic assembly is a way for spring to meet bean dependencies! Spring will automatically find it in the context and automatically assemble properties for the bean.

There are three ways to assemble in spring

  1. Configuration displayed in XML

  2. Display configuration in Java

  3. Implicit auto assembly bean

    name explain
    no The default value indicates that automatic assembly is not used, and bean dependencies must be defined through the ref element.
    byName Automatically assemble according to the name of the property. If the name of a bean is the same as that of a property in another bean, the bean will be automatically assembled into the property.
    byType It is automatically assembled according to the data type of property. If the data type of one bean is compatible with the data type of property in another bean, it is automatically assembled.
    constructor Similar to bytype, bytype mode is automatically assembled according to the data type of construction method parameters.
    Autodetect (not supported in version 3.0) If there is a default construction method in the bean, use the constructor mode, otherwise use the bytype mode.

2.5.1.byName

<!--
Byname: it will automatically find the beanid corresponding to the value after the set method of its own object in the container context!
-->
<bean autowire="byName">
    <property name="name" value="wangyanling"/>
</bean>

2.5.2.byType

<bean/>
    <bean/>
    <!--
    Byname: it will automatically find the beanid corresponding to the value after the set method of its own object in the container context!
    Bytype: it will automatically find beans with the same object attribute type in the container context!
    -->
    <bean autowire="byType">
        <property name="name" value="WANGAYNLING"/>
    </bean>

2.5.3. annotation

jdk1. 5 supported annotations, spring 2 5 supports annotation!

To use notes:

  1. Import context constraint

  2. Configuration annotation support: Context: annotation config/

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config/>
    
    </beans>
    
    

@Autowired

@Autowired is automatically transferred by type and does not support ID matching. byType
You need to import the package of spring AOP!
You can use it directly on the attribute! It can also be used in set mode!

Using Autowired, we don’t need to write the set method, provided that the automatically assembled attribute exists in the IOC container and conforms to the name byname.

 @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;

@Nullable // the field is marked with this annotation, indicating that the field can be null

Or if the required property of Autowired is false, it indicates that the object can be null and can be null

The Autowired annotation can only be anything else. When there is only one type injected into the IOC container, it is assembled through bytype. When there are multiple objects of agreed type in the injection container, it is assembled according to byname

If the environment of @ Autowired auto assembly is complex and the auto assembly cannot be completed through an annotation [@ Autowired], we can use @ qualifier (value = “XXX”) to configure the use of @ Autowired and specify a unique bean object injection.

@Qualifier

@Autowired is automatically assembled according to the type. With @ qualifier, it can be automatically assembled according to byname
@Qualifier cannot be used alone.

public class People {
    private String name;
    @Autowired
    @Qualifier("cat")
    private Cat cat;
    @Autowired
    @Qualifier("dog")
    private Dog dog;
}

@Resource annotation

  • @If the resource has a specified name attribute, first search the assembly by name according to the attribute;
  • Secondly, assemble in the default byname mode;
  • If none of the above is successful, it will be assembled automatically by bytype.
  • If they are not successful, an exception is reported.
public class People {
    private String name;
    @Resource(name = "cat")
    private Cat cat;
    @Resource(name = "dog")
    private Dog dog;

Summary
@Similarities and differences between Autowired and @ resource:

@Both Autowired and @ resource can be used to assemble beans. Can be written on a field or on a setter method.

@Autowired is assembled by type by default (belonging to the spring specification). By default, dependent objects must exist. If null value is allowed, its required property can be set to false, such as @ Autowired (required = false). If we want to use name assembly, it can be used in combination with @ qualifier annotation

@Resource (belonging to J2EE complex), which is assembled by name by default, and the name can be specified through the name attribute. If the name attribute is not specified, when the annotation is written on the field, the default is to take the field name to search by name. If the annotation is written on the setter method, the default is to take the attribute name for assembly. Assemble by type when no bean matching the name is found. However, it should be noted that once the name attribute is specified, it will only be assembled by name.

They have the same function. They inject objects by annotation, but the execution order is [email protected] Autowired bytype first, @ resource byname first.

2.6. IOC annotation

@Annotation name (attribute name = attribute value)

2.6.1. Annotations and explanations used by spring

annotation explain
@Controller Combined annotation (combined with @ Component annotation) is applied in MVC layer (control layer). Dispatcherservlet will automatically scan the class annotated with this annotation, and then map the web request to the method annotated with @ requestmapping.
@Service Composite annotation (composed of @ Component annotation) is applied in the service layer (business logic layer)
@Repository Combined annotation (combined with @ Component annotation) is applied in Dao layer (data access layer)
@Component Indicates that an annotated class is a “component” and becomes a spring managed bean. These classes are considered candidates for automatic detection when annotation based configuration and classpath scanning are used. At the same time, @ component is also a meta annotation.
@Autowired Tools provided by spring (automatically injected by spring’s dependency injection tools (beanpostprocessor, beanfactorypost processor))
@Resource Notes provided by jsr-250
@Inject Notes provided by jsr-330
@Configuration Declare that the current class is a configuration class (equivalent to a spring configuration XML file)
@ComponentScan Automatically scan and register all classes using @ service, @ component, @ controller, @ repository under the specified package
@Bean Annotation on the method, declare the return value of the current method as a bean. The init () method and destroy () method can be defined in the class corresponding to the returned bean, and then defined in @ bean (initmethod = “init”, destroymethod = “destroy”), execute init after construction and destroy before destruction.
@Aspect Declare a facet (that is, it’s an additional feature)
@After The post advice is executed before the original method.
@Before Pre advice is executed after the original method.
@Around Around advice: execute before the original method is executed, and then execute after the original method is executed (@ around can implement the other two kinds of advice)
@PointCut Declare pointcuts, that is, define interception rules to determine which methods will be cut in
@Transactional Declare transactions (the general default configuration can meet the requirements. Of course, it can also be customized)
@Cacheable Declare data cache
@EnableAspectJAutoProxy Enable spring support for AspectJ
@Value It’s worth injecting. It is often used with spring El expression language to inject ordinary characters, system attributes, expression operation results, attributes of other beans, file content, URL request content, configuration file attribute values, etc
@PropertySource Specify the file address. Provides a convenient, declarative mechanism for adding a propertysource to the spring environment. Used with the @ configuration class.
@PostConstruct The annotation is on a method, which is executed after the constructor execution is completed.
@PreDestroy Annotation is on a method that executes before the object is destroyed.
@Profile Indicates that a component is eligible to register when one or more specified files are active. Use @ profile annotation classes or methods to select and instantiate different beans in different [email protected] Profile (“dev”) is instantiated when it is represented as dev.
@EnableAsync Enable asynchronous task support. The annotation is on the configuration class.
@Async The annotation indicates that this is an asynchronous method on the method and that all methods of this class are asynchronous methods on the class.
@EnableScheduling Note: on the configuration class, enable support for planned tasks.
@Scheduled Annotation on a method, declaring that the method is a scheduled task. Support multiple types of scheduled tasks: cron, fixdelay, fixrate
@Conditional Create a specific bean based on meeting a specific condition
@Enable* Through simple @ enableTo enable support for a feature. All @ enableThe annotation has an @ import annotation, @ import is used to import configuration classes, which means that these automatically enabled implementations actually import some automatically configured beans (1. Directly import configuration classes, 2. Select configuration classes according to conditions, 3. Dynamically register configuration classes)
@RunWith This is JUnit’s annotation. Spring boot integrates JUnit. Generally used in test classes: @ runwith (springjunit4classrunner. Class) – springjunit4classrunner provides the function of sprng testcontext framework in JUnit environment
@ContextConfiguration Used to load the configuration ApplicationContext, where the classes attribute is used to load the configuration class: @ contextconfiguration (classes = {testconfig. Class (a custom configuration class)})
@ActiveProfiles The profile used to declare the activity – @ activeprofiles (“prod” (this prod is defined in the configuration class))
@EnableWebMvc Used on the configuration class to enable some default configurations of spring MVC MVC, such as viewresolver, messageconverter, etc. At the same time, when customizing the relevant configuration of spring MVC, you need to do two things: 1 Configuration class inherits webmvcconfigureradapter class 2 You must use this @ enablewebmvc annotation.
@RequestMapping Used to map web requests (access paths and parameters) and process classes and methods. It can be annotated on classes and methods. The @ requestmapping path of the annotation on the method will inherit the path of the annotation on the class. At the same time, the request and response of servlet are supported as parameters, and the media types of request and response are also supported to be configured. There are attributes such as value (path), produces (defining the returned media type and character set), method (specifying the request method), etc.
@ResponseBody Put the return value in the response body. The data is returned, not the page
@RequestBody Allow the parameters of the request to be in the request body, not directly linked after the address. This annotation is placed before the parameter.
@PathVariable Placed in front of the parameter to accept the path parameter.
@RestController Composite annotation, which combines @ controller and @ ResponseBody, can be used when we only develop a control layer that interacts with page data.
@ControllerAdvice It is used on a class to declare a controller advice. It also combines the @ Component annotation and will be automatically registered as a spring bean.
@ExceptionHandler It is used to define the global processing on the method. The intercepted conditions can be filtered through its value attribute: @ exceptionhandler (value = exception. Class) – indicates that all exceptions are intercepted.
@ModelAttribute Add key value pairs to the global. All methods annotated with @ requestmapping can obtain secondary key value pairs (that is, before the request arrives, add attribute and a pair of name value to the model).
@InitBinder Customize webdatabinder through @ initbinder annotation (for methods, the method has a webdatabinder as a parameter, and use webdatabinder to customize data binding in the method, for example, the parameter ID passed by request can be ignored).
@WebAppConfiguration It is generally used in testing and annotated on classes to declare that the loaded ApplicationContext is a webapplicationcontext. Its attribute specifies the location of web resources. The default is Src / main / webapp. We can modify it to: @ webappconfiguration (“Src / main / resources”).
@EnableAutoConfiguration This annotation automatically loads all beans required by the application — which depends on the spring boot’s lookup in the classpath. This annotation combines the @ import annotation, which imports the enableautoconfigurationimportselector class, which uses springfactoryesloader Loaderfactorynames method to scan with meta-inf / spring The jar package of the factories file. Spring Factories declare which automatic configurations are available.
@SpingBootApplication The main purpose of spring boot’s core annotation is to enable automatic configuration. It is also a composite annotation, which mainly combines @ configurer, @ enableautoconfiguration (core) and @ componentscan. You can turn off specific autoconfiguration through @ springbootapplication (exclude = {class name of autoconfiguration you want to turn off. Class}).
@ImportResource Although spring advocates zero configuration, it still provides support for XML files. This annotation is used to load XML configuration. Example: @ importresource ({“classpath”)
@ConfigurationProperties The properties property is associated with a bean and its properties to achieve type safe configuration. Example: @ configurationproperties (prefix = “author”, locations = {“classpath
@ConditionalOnBean Conditional annotation. When there is a specified bean in the container.
@ConditionalOnClass Conditional annotation. When there is a specified class under the class path.
@ConditionalOnExpression Conditional annotation. Based on the spel expression as the judgment condition.
@ConditionalOnJava Conditional annotation. The judgment condition is based on the JVM version.
@ConditionalOnJndi Conditional annotation. Finds the specified location if JNDI exists.
@ConditionalOnMissingBean Conditional annotation. When no bean is specified in the container.
@ConditionalOnMissingClass Conditional annotation. When there is no specified class in the classpath.
@ConditionalOnNotWebApplication Conditional annotation. The current project is not a web project.
@ConditionalOnResource Conditional annotation. Whether the classpath has the specified value.
@ConditionalOnSingleCandidate Conditional annotation. When there is only one specified bean in the container, although the latter has multiple, it specifies the preferred bean.
@ConditionalOnWebApplication Conditional annotation. When the current project is a web project.
@EnableConfigurationProperties Annotation on the class, declare to enable attribute injection and use @ Autowired injection. Example: @ enableconfigurationproperties (httpencodingproperties. Class).
@AutoConfigureAfter Configure after the specified auto configuration class. Example: @ autoconfiguraeafter (webmvcoautoconfiguration. Class)

2.6.1.1. Creating annotations for objects

  • @Component (mark that the current class is a component in the spring container)
  • @Repository (generally used for persistence layer)
  • @Service (generally used for business layer)
  • @Controller (generally used for presentation layer)

2.6.1.2 annotation of injected data

  • @Autowired: automatic injection by type, commonly used on variables; If the only type in the container is the same as the variable type of the annotation, the automatic injection can be successful. When there are multiple beans matching, search according to the variable name. If it is not found, the injection fails.

  • @Qualifier (“userdaoimpl”): used in combination with @ Autowired to inject beans with specified names;It cannot be used alone on the member variables of a class; It can be used separately in method parameters;

  • @Resource: equivalent to @ Autowired automatic injection, while @ resource (name = “XXX”) injection of the specified bean is equivalent to using @ Autowired and @ qualifier (“userdaoimpl”) annotations at the same time.

    The above three annotations can only inject other bean types, not basic data types, string and complex types; Complex types can only be injected through XML files.

  • @Value: inject basic data type and string type. Specify the value of the data, written as ${expression}.

2.6.1.3 notes on changing the scope of action

  • @Scope: the values include singleton single instance (default) and prototype multiple instances

2.6.1.4 notes related to and life cycle

@PostConstruct
public void init() {
    System. out. Println ("initialization Annotation");
}
@PreDestroy
public void destroy() {
    System. out. Println ("destroy Annotation");
}

These two annotations have the same function as init method and destroy method in the bean tag.

2.6.1.5. New annotation

  • @Configuration: used on the class to indicate that the current class is a configuration class

  • @Componentscan (basepackages = “com. WYL”): scan package notes: equivalent to the configuration in the following line

    <!--<context:component-scan base-package="com.wyl"/>-->
    
    
  • @Bean: write on the method in the configuration class and inject the object returned by the method into the spring container. When the annotated method has parameters, it will find the bean object in the container, which is the same as the @ Autowired annotation.

  • @PropertySource(“classpath:db.properties): Specifies the location of the database configuration file

  • @Import: there are multiple configuration files. Use this annotation to import other configuration files.

2.6.1.6. Spring test annotation

@RunWith(SpringJUnit4ClassRunner.class)
@Contextconfiguration (classes = applicationconfig. Class) pure annotation
//@ contextconfiguration (locations = "classpath: ApplicationContext. XML") XML configuration file
public class SpringTest {

    @Autowired
    private AccountServiceImpl accountService;

    @Test
    public void findAll(){
        List<Account> accountList = accountService.findAll();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }

}

@Runwith (spring junit4classrunner. Class): replace the original JUnit runner execution method and use spring’s own execution method.

@Contextconfiguration (classes = applicationconfig. Class): if the spring container is created using annotations, use classes;

@ContextConfiguration(locations = “classpath:ApplicationContext.xml“): method of using XML configuration file

2.6.2. Creating beans based on XML

public class User {
    private Integer id;
    private String name;
}

<?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 >
        <property name="id" value="1"></property>
        <property name="name" value="wyl"></property>
    </bean>
</beans>

@test
public void UserTest{
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("Bean.xml");
        User userInfo=(User)context.getBean("user");
        System.out.println(userInfo);
}

2.6.3.Annotation based on @ configuration and @ bean

Configuration configuration class

@Configuration
public class MyTestConfig {
    //The ID of the bean defaults to the method name
    @Bean
    public User user(){
        User user =new User();
        user. Setname ("Wang Yanling");
        user.setId(2);
        return user;
    }
}
@test
public void UserTest{
    AnnotationConfigApplicationContext context=new                          AnnotationConfigApplicationContext(MyTestConfig.class);
        User userInfo=(User)context.getBean("user");
        System.out.println(userInfo.toString());
        }

3. Spring core AOP

AOP (aspect oriented programming): aspect oriented programming, which enhances the function of the code without modifying the source code. AOP can isolate each part of business logic, reduce the coupling between each part of business logic, improve the reusability of program, and improve the efficiency of development.

Do you really know what spring is? Spring Quick Start Guide

image-20210901112213781

3.1. AOP implementation principle agent mode

Proxy mode, create a proxy object to implement the same interface as the proxy object, so it has the same functions as the proxy object, and enhance the original method on this basis.

  • Static proxy, manually implement a proxy class
  • Dynamic proxy, by reflecting the dynamic implementation of the proxy class

3.1.1 static proxy

Steps:

  1. Abstract role: generally implemented using interfaces or abstract classes

    public interface Rent {
        public void rent();
    }
    
    
  2. Real role: the role represented

    public class Host implements Rent{
        @Override
        public void rent() {
            System. out. Println ("landlord rents house!");
        }
    }
  3. Agent role: agent real role; After representing a real role, you usually do some ancillary operations

    public class Proxy {
        private Host host;
        public Proxy(){
    
        }
        public Proxy(Host host){
            this.host=host;
        }
        public void rent(){
            seeHouse();
    
            host.rent();
            hetong();
            fare();
        }
        public void seeHouse(){
            System. out. Println ("intermediary shows you the house");
        }
        public void fare(){
            System. out. Println ("collect intermediary fee!");
        }
        public void hetong(){
            System. out. Println ("signing lease and collection contract");
        } 
    
    }
  4. Customer: use the agent role to perform some operations

public class Client {
    public static void main(String[] args) {
        Host host=new Host();
        //host.rent();
        Proxy proxy=new Proxy(host);
        proxy.rent();
    }
}

Benefits:

  • It can make our real role more pure Stop paying attention to some public things
  • Public business is done by agents The division of business is realized,
  • When the public business expands, it becomes more centralized and convenient

Disadvantages:

  • With more classes and more proxy classes, the workload becomes larger Reduced development efficiency
    We want the advantages of static proxy, but we don’t want the disadvantages of static proxy. Therefore, we have dynamic proxy

3.1.2. Dynamic agent

The proxy class of dynamic proxy is generated dynamically The proxy class of static proxy is written in advance

Dynamic agents fall into two categories:

  1. Dynamic agent based on interface — JDK dynamic agent

    //Abstract role: rent a house
    public interface Rent {
        public void rent();
    }
    //Real role: landlord, the landlord wants to rent the house
    public class Host implements Rent{
        public void rent() {
            System. out. Println ("house rental");
        }
    }
    //Agent: Intermediary
    public class ProxyInvocationHandler implements InvocationHandler {
        private Rent rent;
    
        public void setRent(Rent rent) {
            this.rent = rent;
        }
    
        //Generate an agent class, focusing on the second parameter to obtain the abstract role to be represented! It used to be a role, but now it can represent a kind of role
        public Object getProxy(){
            return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    rent.getClass().getInterfaces(),this);
        }
    
        //Proxy: proxy class method: the method object of the calling handler of the proxy class
        //Process method calls on proxy instances and return results
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            seeHouse();
            //Core: essence is realized by reflection!
            Object result = method.invoke(rent, args);
            fare();
            return result;
        }
    
        //House viewing
        public void seeHouse(){
            System. out. Println ("show tenants");
        }
        //Intermediary fee
        public void fare(){
            System. out. Println ("collection of intermediary fees");
        }
    }
    //Tenant
    public class Client {
    
        public static void main(String[] args) {
            //Real role
            Host host = new Host();
            //Call handler for proxy instance
            ProxyInvocationHandler pih = new ProxyInvocationHandler();
            pih. setRent(host); // Put the real character in!
            Rent proxy = (Rent)pih. getProxy(); // Dynamically generate the corresponding proxy class!
            proxy.rent();
        }
    
    }
  2. Class based dynamic proxy – cglib

//Proxied object
Account account = new Account();
Account o = (Account) Enhancer.create(account.getClass(), new MethodInterceptor() {
    /**
    *The method of the proxy object is executed before execution
    *@ param obj proxied object
    *@ param method method
    *@ param objects parameter
    *@ param methodproxy the object of the proxy that currently executes the method
    *@ return has the same return value as the method of the proxy object
    *@ throws throwable exception
    */
    @Override
    public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System. out. Println ("before enhancement...);
        Object invoke = method.invoke(account, objects);
        System. out. Println ("enhanced...);
        return invoke;
    }
});
o.findAll();

3.2. AOP terminology

  • Joinpoint: refers to methods. Methods that can be enhanced by dynamic proxy are connection points. Spring only supports connection points of method types
  • Pointcut: defines which joinpoint join points (Methods) to intercept enhancements.The enhanced method is called a pointcut, and all methods can be regarded as a connection point. Only enhanced methods are called pointcuts.
  • Advice: after intercepting the jointpoint, all you have to do is notify. Notification types: pre notification, post notification, final notification, surround notification and exception notification.
  • Introduction: a special notification that can dynamically add some methods or fields for a class at run time without modifying the code.
  • Target: the target object of the proxy
  • Weaving: the process of applying enhancements to the target object to create a new proxy object (the process of adding new function code). Spring uses dynamic proxy weaving, while AspectJ uses compile time and class loading weaving.
  • Proxy: after a class is enhanced by AOP weaving, a resulting proxy class is generated.
  • Aspect: a combination of pointcuts and notifications (Introductions).
Do you really know what spring is? Spring Quick Start Guide

3.3. Using spring to implement AOP

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

3.3.1. Implemented through spring API

//Interface and service
public interface UserService {

    public void add();

    public void delete();

    public void update();

    public void search();

} 
public class UserServiceImpl implements UserService{

    @Override
    public void add() {
        System. out. Println ("add user");
    }

    @Override
    public void delete() {
        System. out. Println ("delete user");
    }

    @Override
    public void update() {
        System. out. Println ("update user");
    }

    @Override
    public void search() {
        System. out. Println ("query user");
    }
}
//Strengthen
public class AfterLog implements AfterReturningAdvice {
    //ReturnValue return value
    //Method called method
    //Args parameter of the object of the called method
    //Target the called target object
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System. out. Println ("executed" + target. Getclass() getName()
        +"+ method Getname() + "method,"
        +"Return value:" + returnValue);
    }
}
<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- Register beans -- >
    <bean/>
    <bean/>
    <bean/>

    <!-- AOP configuration -- >
    <aop:config>
        <!-- Pointcut expression: expression matches the method to execute -- >
        <aop:pointcut expression="execution(* com.wyl.service.UserServiceImpl.*(..))"/>
        <!-- Execute surround; Advice ref execution method Pointcut ref pointcut -- >
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.search();
    }
}

3.3.2. Custom classes to implement AOP

//Cut in class
public class DiyPointcut {

    public void before(){
        System. out. Println ("--------- before method execution ------");
    }
    public void after(){
        System. out. Println ("--------- after method execution ---------------");
    }

}
<!-- The second way is to customize the implementation -- >
<!-- Register beans -- >
<bean/
<!-- AOP configuration -- >
<aop:config>
    <!-- The second way: use the tag implementation of AOP -- >
    <aop:aspect ref="diy">
        <aop:pointcut expression="execution(* com.wyl.service.UserServiceImpl.*(..))"/>
        <aop:before pointcut-ref="diyPonitcut" method="before"/>
        <aop:after pointcut-ref="diyPonitcut" method="after"/>
    </aop:aspect>
</aop:config>
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

3.3.3. Implementing AOP with annotations

//Annotation implemented enhancement class
package com.wyl.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AnnotationPointcut {
    @Before("execution(* com.wyl.service.UserServiceImpl.*(..))")
    public void before(){
        System. out. Println ("--------- before method execution ------");
    }

    @After("execution(* com.wyl.service.UserServiceImpl.*(..))")
    public void after(){
        System. out. Println ("--------- after method execution ---------------");
    }

    @Around("execution(* com.wyl.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System. out. Println ("before surround");
        System. out. Println ("signature: + JP. Getsignature());
        //Execute target method
        Object proceed = jp.proceed();
        System. out. Println ("after surround");
        System.out.println(proceed);
    }
}

4. Transaction and jdbctemplate

4.1. Use of jdbctemplate

Introductory case:

//Spring's own data source
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("root");
JdbcTemplate template = new JdbcTemplate(dataSource);

List<Account> accountList = template.query("select * from account", new BeanPropertyRowMapper<>(Account.class));
for (Account account : accountList) {
    System.out.println(account);
}

Specific usage of addition, deletion and modification:

@Autowired
private JdbcTemplate jdbcTemplate;

//Add
@Test
public void insert(){
    String sql = "insert into account(name, money) VALUES (?,?)";
    Account account1 = new Account();
    account1. Setname ("diga");
    account1.setMoney(10000F);
    jdbcTemplate.update(sql, account1.getName(), account1.getMoney());
    find();
}

//Delete
@Test
public void delete(){
    String sql = "delete from account where id = ?";
    jdbcTemplate.update(sql, 6);
    find();
}

//Renew
@Test
public void update(){
    List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<>(Account.class), 1);
    Account account = accounts.get(0);
    account. Setname ("Taylor");
    String sql = "update account set name = ? where id = ?";
    jdbcTemplate.update(sql, account.getName(),account.getId());
    find();
}

//Query all
@Test
public void find(){
    List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<>(Account.class));
    for (Account account : accountList) {
        System.out.println(account);
    }
}

//Query a bean
@Override
public Account findByName(String name) {
    String sql = "select * from account where name = ?";
    return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), name);
}

//Query an object
@Test
public void findOne(){
    String sql = "select count(id) from account";
    Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
    System.out.println(integer);
}

4.2. Spring configuration transaction

There are two ways to manage transactions in spring: declarative transaction management and programmatic transaction management;

  • Declarative transaction management:

    1. XML configuration file:

    1. Configure transaction manager
    <bean>
        <property name="dataSource" ref="dataSource"/></bean>
    
    2. Configure notifications
    <!--  Configure notification / enhancement of transactions -- >
    <tx:advice>
        <!--  Configure transaction properties -- >
        <!--  Isolation: transaction isolation level. The isolation level of the database is used by default
             No rollback for: specifies an exception. All exceptions except this exception are rolled back.
             Propagation: transaction propagation behavior. It is required by default. There must be transactions. Add, delete, change and set required. Query and set supports
             Read only: whether to read only. Only queries can be set to true. The default is false. Read / write is supported.
             Rollback for: specifies an exception. If this exception occurs, it will be rolled back. Other exceptions will not be rolled back.
             Timeout: transaction timeout, default - 1, never timeout. Specified in seconds. -- >
        <tx:attributes>
            <!--  Specifies the method on which the rule is added -- >
            <tx:method name="transfer*"/>
        </tx:attributes>
    </tx:advice>
    
    3. The transaction manager is associated with a pointcut expression
    <aop:config>
        <!--  Add transactions to all methods of all classes under the service package -- >
        <aop:pointcut expression="execution(* com.sample.service.*.*(..))"/>
        <!--  Associate a transaction manager with a pointcut expression -- >
        <aop:advisor advice-ref="interceptor" pointcut-ref="commonPointcut"/>
    </aop:config>

    2. Annotation:

    1. Configure transaction manager
    <bean>
        <property name="dataSource" ref="dataSource"/></bean>
    
    2. Enable support for transaction annotations
    <!--  Enable support for transaction annotations -- >
    <tx:annotation-driven/>
    
    3. Add comments on the class to which you want to add things: @ transactional

    3. Pure annotation

    @Configuration
    @ComponentScan("com.sample")
    //Equivalent to < TX: annotation driven / >
    @EnableTransactionManagement
    @PropertySource("classpath:db.properties")
    public class AppConfig {
    
        @Value("${db.driver}")
        private String driver;
        @Value("${db.url}")
        private String url;
        @Value("${db.username}")
        private String username;
        @Value("${db.password}")
        private String password;
    
        @Bean
        public DruidDataSource dataSource(){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    
        @Bean
        public JdbcTemplate jdbcTemplate(){
            return new JdbcTemplate(dataSource());
        }
    
        @Bean
        public DataSourceTransactionManager transactionManager(){
            return new DataSourceTransactionManager(dataSource());
        }
    
    }
    
    ==========
    Add @ transactional annotation on the class
  • Programming transaction management: realize transaction management through code, and manually start transaction, commit and rollback.