Get started Spring

@recard:CodePianist
@Date:2022/1/11

Two core mechanisms of Spring framework (IoC and AOP)

  • IoC (control inversion) / DI (dependency injection)
  • AOP (aspect oriented programming)

Spring is an enterprise level development framework and a software design level framework. Its advantage is that it can layer applications and developers can choose components independently.

MVC: Struts2,Spring MVC

ORMapping: Hibernate,MyBatis,Spring Data

IoC

Ioc introduction

  • Control reversal (IoC/DI)

Control: who controls the creation of objects? Traditional application objects are created by the program itself. After using Spring, objects are created by Spring
Inversion: the program itself does not create an object, but becomes a passive receiving object.
Dependency injection: it uses the set method to inject
IOC is a programming idea, which changes from active programming to passive reception. The so-called IOC means that objects are created, managed and assembled by Spring

IoC quick start

  • Create Maven project, POM XML add dependency
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.southwind</groupId>
    <artifactId>aispringioc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
    </dependencies>

</project>
  • Create entity class Student
package com.southwind.entity;

import lombok.Data;

@Data
public class Student {
    private long id;
    private String name;
    private int age;
}
  • Traditional development method, manual new Student
Student student = new Student();
student.setId(1L);
student.setName("Zhang San");
student.setAge(22);
System.out.println(student);
  • Create objects through IoC, add objects to be managed in the configuration file, XML format configuration file, and file name can be customized.
<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
">

    <bean id="student" class="com.southwind.entity.Student">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="22"></property>
    </bean>

</beans>
  • Get the object from IoC through id.
//Load profile
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);

Ioc basic configuration

  • If an alias is added, the object can also be obtained through the alias

    <alias name="user" alias="userAlias"/>
    
  • Manage objects by configuring bean tags.

    • id: object name.

    • Class: the template class of the object (all classes managed by IoC container must have a parameterless constructor, because Spring creates objects through reflection mechanism and calls parameterless construction)

  • The member variables of the object are assigned through the property tag.

    • Name: member variable name.
    • Value: value of member variable (basic data type, String can be assigned directly; if it is other reference types, it cannot be assigned through value)
    • ref: assign another bean in IoC to the current member variable (DI)
    <bean id="student" class="com.southwind.entity.Student">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="22"></property>
        <property name="address" ref="address"></property>
    </bean>
    
    <bean id="address" class="com.southwind.entity.Address">
        <property name="id" value="1"></property>
        <property name="name" value="Science and technology road"></property>
    </bean>
    
  • import

    Import is generally used for team development. It can import and merge multiple configuration files into one
    Suppose that there are many people developing in the project. These three people are responsible for different class development. Different classes need to be registered in different beans. We can import everyone's beans XML is merged into a total

    	<import resource="applicationContext1.xml"/>
    

IoC underlying principle

  • Read the configuration file and parse the XML.
  • Instantiate all bean s configured in the configuration file through the reflection mechanism.
package com.southwind.ioc;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ClassPathXmlApplicationContext implements ApplicationContext {
    private Map<String,Object> ioc = new HashMap<String, Object>();
    public ClassPathXmlApplicationContext(String path){
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read("./src/main/resources/"+path);
            Element root = document.getRootElement();
            Iterator<Element> iterator = root.elementIterator();
            while(iterator.hasNext()){
                Element element = iterator.next();
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                //Create objects through reflection mechanism
                Class clazz = Class.forName(className);
                //Get the parameterless constructor and create the target object
                Constructor constructor = clazz.getConstructor();
                Object object = constructor.newInstance();
                //Assign a value to the target object
                Iterator<Element> beanIter = element.elementIterator();
                while(beanIter.hasNext()){
                    Element property = beanIter.next();
                    String name = property.attributeValue("name");
                    String valueStr = property.attributeValue("value");
                    String ref = property.attributeValue("ref");
                    if(ref == null){
                        String methodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
                        Field field = clazz.getDeclaredField(name);
                        Method method = clazz.getDeclaredMethod(methodName,field.getType());
                        //Convert value according to the data type of the member variable
                        Object value = null;
                        if(field.getType().getName() == "long"){
                            value = Long.parseLong(valueStr);
                        }
                        if(field.getType().getName() == "java.lang.String"){
                            value = valueStr;
                        }
                        if(field.getType().getName() == "int"){
                            value = Integer.parseInt(valueStr);
                        }
                        method.invoke(object,value);
                    }
                    ioc.put(id,object);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e){
            e.printStackTrace();
        } catch (NoSuchMethodException e){
            e.printStackTrace();
        } catch (InstantiationException e){
            e.printStackTrace();
        } catch (IllegalAccessException e){
            e.printStackTrace();
        } catch (InvocationTargetException e){
            e.printStackTrace();
        } catch (NoSuchFieldException e){
            e.printStackTrace();
        }
    }

    public Object getBean(String id) {
        return ioc.get(id);
    }
}

How IOC creates objects

1. Create objects using parameterless construction by default

Get bean s through runtime classes

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Student student = (Student) applicationContext.getBean(Student.class);
System.out.println(student);

There is a problem with this method. An object of a data type in the configuration file can only have one instance, otherwise an exception will be thrown because there is no unique bean.

2. Create bean s through parametric construction

  • Create the corresponding parameterized constructor in the entity class.
  • 1 variable name assignment
<bean id="student3" class="com.southwind.entity.Student">
    <constructor-arg name="id" value="3"></constructor-arg>
    <constructor-arg name="name" value="Xiao Ming"></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
    <constructor-arg name="address" ref="address"></constructor-arg>
</bean>
  • 2 subscript assignment
<bean id="student3" class="com.southwind.entity.Student">
    <constructor-arg index="0" value="3"></constructor-arg>
    <constructor-arg index="2" value="18"></constructor-arg>
    <constructor-arg index="1" value="Xiao Ming"></constructor-arg>
    <constructor-arg index="3" ref="address"></constructor-arg>
</bean>
  • 3 variable type
<bean id="user1" class="com.yang.entity.User">
    <constructor-arg type="int" value="18"/>
    <constructor-arg type="java.lang.String" value="Zhang San"/>
</bean>

3.IoC creates bean s through factory mode in two ways:

  • Static factory method
  • Example factory method

Static factory method

package com.southwind.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
    private long id;
    private String name;
}
package com.southwind.factory;

import com.southwind.entity.Car;

import java.util.HashMap;
import java.util.Map;

public class StaticCarFactory {
    private static Map<Long, Car> carMap;
    static{
        carMap = new HashMap<Long, Car>();
        carMap.put(1L,new Car(1L,"bmw"));
        carMap.put(2L,new Car(2L,"Benz"));
    }

    public static Car getCar(long id){
        return carMap.get(id);
    }
}
<!-- Configure static factory creation Car -->
<bean id="car" class="com.southwind.factory.StaticCarFactory" factory-method="getCar">
    <constructor-arg value="2"></constructor-arg>
</bean>

Example factory method

package com.southwind.factory;

import com.southwind.entity.Car;

import java.util.HashMap;
import java.util.Map;

public class InstanceCarFactory {
    private Map<Long, Car> carMap;
    public InstanceCarFactory(){
        carMap = new HashMap<Long, Car>();
        carMap.put(1L,new Car(1L,"bmw"));
        carMap.put(2L,new Car(2L,"Benz"));
    }

    public Car getCar(long id){
        return carMap.get(id);
    }
}
<!-- Configure instance factory bean -->
<bean id="carFactory" class="com.southwind.factory.InstanceCarFactory"></bean>

<!-- Compensation instance factory creation Car -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
    <constructor-arg value="1"></constructor-arg>
</bean>

DI dependency injection

IoC is responsible for creating the object, and DI is responsible for completing the dependency injection of the object by configuring the ref attribute of the property tag

1. Constructor injection

  • No parameter

  • Have reference

2.set mode injection [ key ]

...

  • Inject collections into bean s
<bean id="student" class="com.southwind.entity.Student">
    <property name="id" value="2"></property>
    <property name="name" value="Li Si"></property>
    <property name="age" value="33"></property>
    <property name="addresses">
        <list>
            <ref bean="address"></ref>
            <ref bean="address2"></ref>
        </list>
    </property>
</bean>

<bean id="address" class="com.southwind.entity.Address">
    <property name="id" value="1"></property>
    <property name="name" value="Science and technology road"></property>
</bean>

<bean id="address2" class="com.southwind.entity.Address">
    <property name="id" value="2"></property>
    <property name="name" value="High tech Zone"></property>
</bean>

3.p label injection

p namespace is a simplified operation of IoC / DI. Using p namespace can more easily complete bean configuration and dependency injection between beans.

<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
">

    <bean id="student" class="com.southwind.entity.Student" p:id="1" p:name="Zhang San" p:age="22" p:address-ref="address"></bean>

    <bean id="address" class="com.southwind.entity.Address" p:id="2" p:name="Science and technology road"></bean>

</beans>

Scope of Bean

Spring managed beans are generated according to the scope and represent the scope of the bean. There are four kinds in total. The default value is singleton.

  • Singleton: singleton, indicating that the bean obtained through the IoC container is unique.
  • Prototype: prototype, indicating that the bean s obtained through the IoC container are different.
  • Request: request, indicating that it is valid in an HTTP request.
  • Session: reply, indicating that it is valid in a user session.

request and session are only applicable to Web projects. In most cases, singletons and prototypes are used more.

prototype mode when the business code obtains the bean in the IoC container, Spring calls the parameterless construct to create the corresponding bean.

singleton mode whether the business code gets the bean in the IoC container or not, Spring is loading Spring The bean is created when the XML.

Spring inheritance

Different from Java inheritance, Java is class level inheritance, and subclasses can inherit the internal structure information of the parent class; Spring is object level inheritance. Child objects can inherit the attribute values of parent objects.

<bean id="student2" class="com.southwind.entity.Student">
    <property name="id" value="1"></property>
    <property name="name" value="Zhang San"></property>
    <property name="age" value="22"></property>
    <property name="addresses">
        <list>
            <ref bean="address"></ref>
            <ref bean="address2"></ref>
        </list>
    </property>
</bean>

<bean id="address" class="com.southwind.entity.Address">
    <property name="id" value="1"></property>
    <property name="name" value="Science and technology road"></property>
</bean>

<bean id="address2" class="com.southwind.entity.Address">
    <property name="id" value="2"></property>
    <property name="name" value="High tech Zone"></property>
</bean>

<bean id="stu" class="com.southwind.entity.Student" parent="student2">
    <property name="name" value="Li Si"></property>
</bean>

Spring's inheritance focuses on specific objects, not classes, that is, instantiated objects of two different classes can complete inheritance, on the premise that the child object must contain all properties of the parent object, and other properties can be added on this basis.

Spring dependency

Similar to inheritance, dependency also describes the relationship between beans. After configuring dependency, the dependent beans must be created first, and then the dependent beans. A depends on B, and then B, and then 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-3.2.xsd
                           ">

    <bean id="student" class="com.southwind.entity.Student" depends-on="user"></bean>

    <bean id="user" class="com.southwind.entity.User"></bean>

</beans>

IoC Autowire

IoC is responsible for creating objects and DI is responsible for completing the dependency injection of objects by configuring the ref attribute of the property tag. At the same time, Spring provides another simpler dependency injection method: automatic loading without manually configuring the property. The IoC container will automatically select bean s to complete the injection.

There are two ways of automatic loading:

  • byName: auto load by attribute name
  • byType: automatically loaded by the data type of the attribute

byName

<bean id="cars" class="com.southwind.entity.Car">
    <property name="id" value="1"></property>
    <property name="name" value="bmw"></property>
</bean>

<bean id="person" class="com.southwind.entity.Person" autowire="byName">
    <property name="id" value="11"></property>
    <property name="name" value="Zhang San"></property>
</bean>

byType

<bean id="car" class="com.southwind.entity.Car">
    <property name="id" value="2"></property>
    <property name="name" value="Benz"></property>
</bean>

<bean id="person" class="com.southwind.entity.Person" autowire="byType">
    <property name="id" value="11"></property>
    <property name="name" value="Zhang San"></property>
</bean>

byType should be noted that if there are two or more qualified bean s at the same time, automatic loading will throw an exception.

Summary

When byName, it is necessary to ensure that the IDs of all beans are unique, and the bean needs to be consistent with the value of the set method of the automatically injected attribute
When byType, you need to ensure that the class es of all beans are unique, and the bean needs to be consistent with the type of automatically injected properties

Automatic assembly using annotations

<?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"
      xmlns:aop="http://www.springframework.org/schema/aop"
      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
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

   <!--Enable annotation support-->
   <context:annotation-config/>
</beans>

@Autowired

public class People {
    //If the required property of Autowired is defined as false, it means that the object can be null, otherwise it is not allowed to be empty
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;

@Resource

public class People {
Not specified name Value, judge first byName and byType´╝îOne that can inject is successful
    @Resource(name = "xxxx")
    private Cat cat;

Using annotation development

Using annotation development

  • To use annotations, you need to import context constraints and add annotation support
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--Enable annotation support-->
    <context:annotation-config/>
    <!--Specify the package to be scanned, and the annotations under the package will take effect-->
    <context:component-scan base-package="com.yang"/>

</beans>
  • 1. bean injection uses @ Componet annotation

    //@Component is equivalent to < bean id = "user" class = "com. Yang. Entity. User" / >
    @Component
    public class User {
        String name;
    }
    

    2. Attribute injection uses @ Value annotation

    //@Component is equivalent to < bean id = "user" class = "com. Yang. Entity. User" / >
    @Component
    public class User {
        //@Value("yang") is equivalent to < property name = "name" value = "Yang" / >
        @Value("ljx")
        String name;
        
        @Value("cjh")
        public void setName(String name) {
            this.name = name;
        }
    }
    

    3. Derived notes
    @Componet has several derived annotations. In web development, we will layer according to the mvc three-tier architecture!

    dao layer [@ Repository]
    Service layer [@ service]
    Controller layer [@ controller]

AOP

ps: focus of agent mode

AOP: Aspect Oriented Programming.

AOP benefits:

  • Reduce the coupling between modules.
  • Make the system easier to expand.
  • Better code reuse.
  • Non business codes are more centralized and non decentralized, which is convenient for unified management.
  • Business codes are more concise and concise, without the influence of other codes.

AOP is a supplement to object-oriented programming. In runtime, the programming idea of dynamically cutting code into the specified methods and positions of classes is aspect oriented programming. The same location of different methods is abstracted into a facet object, and programming the facet object is AOP.

How to use?

  • Create Maven project, POM XML add
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
</dependencies>
  • Create a calculator interface Cal and define four methods.
package com.southwind.utils;

public interface Cal {
    public int add(int num1,int num2);
    public int sub(int num1,int num2);
    public int mul(int num1,int num2);
    public int div(int num1,int num2);
}
  • Create the implementation class CalImpl of the interface.
package com.southwind.utils.impl;

import com.southwind.utils.Cal;

public class CalImpl implements Cal {
    public int add(int num1, int num2) {
        System.out.println("add The parameters of the method are["+num1+","+num2+"]");
        int result = num1+num2;
        System.out.println("add The result of the method is"+result);
        return result;
    }

    public int sub(int num1, int num2) {
        System.out.println("sub The parameters of the method are["+num1+","+num2+"]");
        int result = num1-num2;
        System.out.println("sub The result of the method is"+result);
        return result;
    }

    public int mul(int num1, int num2) {
        System.out.println("mul The parameters of the method are["+num1+","+num2+"]");
        int result = num1*num2;
        System.out.println("mul The result of the method is"+result);
        return result;
    }

    public int div(int num1, int num2) {
        System.out.println("div The parameters of the method are["+num1+","+num2+"]");
        int result = num1/num2;
        System.out.println("div The result of the method is"+result);
        return result;
    }
}

In the above code, the coupling between log information and business logic is very high, which is not conducive to system maintenance. It can be optimized using AOP. How to implement AOP? It is implemented by using dynamic agent.

Find an agent for the business code and hand over the printing of log information to an agent. In this way, the business code only needs to pay attention to its own business.

package com.southwind.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class MyInvocationHandler implements InvocationHandler {
    //Receive delegate object
    private Object object = null;

    //Return proxy object
    public Object bind(Object object){
        this.object = object;
        return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName()+"The parameters of the method are:"+ Arrays.toString(args));
        Object result = method.invoke(this.object,args);
        System.out.println(method.getName()+"The result is"+result);
        return result;
    }
}

The above is the process of realizing AOP through dynamic proxy, which is complex and difficult to understand. The Spring framework encapsulates AOP. Using the Spring framework, AOP can be realized with the idea of object-oriented.

There is no need to create InvocationHandler in the Spring framework, just create a facet object and complete all non business code in the facet object. The bottom layer of the Spring framework will automatically generate a proxy object according to the facet class and target class.

LoggerAspect

package com.southwind.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LoggerAspect {

    @Before(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))")
    public void before(JoinPoint joinPoint){
        //Get method name
        String name = joinPoint.getSignature().getName();
        //Get parameters
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println(name+"The parameters of the method are:"+ args);
    }

    @After(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))")
    public void after(JoinPoint joinPoint){
        //Get method name
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"Method execution completed");
    }

    @AfterReturning(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        //Get method name
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"The result of the method is"+result);
    }

    @AfterThrowing(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))",throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint,Exception exception){
        //Get method name
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"Method throws an exception:"+exception);
    }

}

Two annotations added at the LoggerAspect class definition:

  • @Aspect: indicates that the class is an aspect class.
  • @Component: inject the object of this class into the IoC container.

Notes added at specific methods:

@Before: indicates the specific location and timing of method execution.

CalImpl also needs to add @ Component to be managed by IoC container.

package com.southwind.utils.impl;

import com.southwind.utils.Cal;
import org.springframework.stereotype.Component;

@Component
public class CalImpl implements Cal {
    public int add(int num1, int num2) {
        int result = num1+num2;
        return result;
    }

    public int sub(int num1, int num2) {
        int result = num1-num2;
        return result;
    }

    public int mul(int num1, int num2) {
        int result = num1*num2;
        return result;
    }

    public int div(int num1, int num2) {
        int result = num1/num2;
        return result;
    }
}

spring. Configure AOP in 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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
">

    <!-- Automatic scanning -->
    <context:component-scan base-package="com.southwind"></context:component-scan>

    <!-- yes Aspect The annotation takes effect, and the proxy object is automatically generated for the target class -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

Context: Component scan will com Scan all classes in Southwind package. If @ Component is added to this class at the same time, scan this class into IoC container, that is, IoC manages its objects.

AOP: AspectJ AutoProxy enables the Spring framework to automatically generate dynamic proxy objects by combining aspect classes and target classes.

  • Facet: an abstract object whose crosscutting concerns are modularized.
  • Notification: work done by cut objects.
  • Target: the notified object, that is, the crosscutting object.
  • Proxies: objects mixed with facets, notifications, and targets.
  • Connection point: notifies the specific location of the business code to be inserted.
  • Tangent point: AOP locates to the connection point through the tangent point.

Integrate Mybatis

https://mp.weixin.qq.com/s/gXFMNU83_7PqTkNZUgvigA

Keywords: Java Spring mvc

Added by sgarcia on Tue, 11 Jan 2022 12:42:31 +0200