Use of ioc and aop in Spring learning notes

Spring learning notes

pom.xml required configuration

​ 1. Specify JDK version

  <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>

​ 2. Dependencies of spring framework

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.9</version>
    </dependency>

I Principle of Ioc

DI is the technical implementation of ioc

Di (dependency injection): dependency injection. You only need to provide the name of the object to be used in the program. All objects are created in the container and managed inside the container.

spring uses di to realize the function of ioc. spring creates objects at the bottom and uses reflection mechanism.

1. How to implement spring container to create objects

  1. Create maven project
  2. Join the maven dependency of Srping
  3. Create classes and xml configuration files of classes and hand them over to the Spring container for management
  4. Test objects created by spring

The spring container creates objects through the tag in the xml configuration file, which has two properties

id and class attribute id are aliases of the class, and class is the fully qualified name of the class. This is done by the map object in the spring container

Put the object into the map and get the object through the key value. The key is the id

The Spring container creates objects and reads resources and beans through ClassPathXmlApplicationContext XML configuration file

    @Test
    public void testDemo(){
        //Create an object by reading the configuration file through ClassPathXmlApplicationContext
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //Get the bean object using the getbean method
        SomeService someService = (SomeService) context.getBean("someService");
        someService.doservice();

    }

II Object creation timing

When the ApplicationContext object is new, it will create objects in all configuration files.

III di: dependency injection, assigning values to object attributes

di syntax classification:

1.set injection: spring calls the set method and uses the set method to complete dependency injection and assignment

1). The injection of simple types (specifying the eight basic types + string types as simple types) is carried out through the property in the bean tag

<bean id="xxx" class="xxx">
	<property name="Property name in class" value="The value of the property"/>
    <property.../>
</bean>

For injection according to the set method, you must ensure that there is the set method corresponding to the attribute in the class.

2). Injection of reference types

<bean id="xxx" class="xxx">
	<property name="Property name in class" ref="other bean Tagged id"/>
</bean>

2. Constructor method injection. spring calls the parameterized constructor of the class to complete parameter injection.

1). The constructor Arg tag is used to inject the constructor arg. The attribute of the tag is index name value ref

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="student" class="com.liyuan.ba03.Student">
        <constructor-arg name="age" value="18"/>
        <constructor-arg name="name" value="Li Yuan"/>
        <constructor-arg name="school" ref="school"/>
    </bean>

    <bean id="school" class="com.liyuan.ba03.School">
        <property name="name" value="Anyang Normal University" />
        <property name="address" value="Xiange Avenue, Wenfeng District, Anyang City, Henan Province"/>
    </bean>
</beans>

3. Automatic injection of reference type: automatic injection is performed through the < bean > tag autowire attribute. There are two methods of injection byname bytype

1).byname implements the injection of reference type attributes by using the same attribute name of the application type in the bean object as the spring (bean in XML configuration file) id name

Syntax:

<bean id="xxx" class="xxx" autowire="byName">
	<property name="xx" value="xxx"/>
    ...Simple type
</bean>

Actual:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="student" class="com.liyuan.ba03.Student" autowire="byName">
        <property name="name" value="Li Yuan"/>
        <property name="age"  value="18" />
<!--        <property name="school" ref="school"/>-->
    </bean>

    <bean id="school" class="com.liyuan.ba03.School">
        <property name="name" value="Xiange Avenue campus of Anyang Normal University" />
        <property name="address" value="Xiange Avenue, Wenfeng District, Anyang City, Henan Province"/>
    </bean>
</beans> 
package com.liyuan.ba04;

public class Student {
    private Integer age;
    private String name;
    private School school;


    public Student() {
    }

    public Student(Integer age, String name, School school) {
        this.age = age;
        this.name = name;
        this.school = school;
    }

    public School getSchool() {
        return school;
    }

    public void setSchool(School school) {
        this.school = school;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", school=" + school+
                '}';
    }
}

2). Attribute injection is performed through bytype, and the class of the attribute in the bean is homologous

Definition criteria of homology: 1 Is the same class

​ 2. It's a father son relationship

​ 3. Is to implement the class interface relationship

Syntax:

<bean id="xxx" class="xxx" autowire="byType">
	<property name="xx" value="xxx"/>
    ...Simple type
</bean>

Actual:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="student" class="com.liyuan.ba03.Student" autowire="byType">
        <property name="name" value="Li Yuan"/>
        <property name="age"  value="18" />
<!--        <property name="school" ref="school"/>-->
    </bean>

    <bean id="myschool" class="com.liyuan.ba03.School">
        <property name="name" value="Xiange Avenue, Anyang Normal University" />
        <property name="address" value="Xiange Avenue, Wenfeng District, Anyang City, Henan Province"/>
    </bean>
</beans> 

IV Implementation of dependency injection based on annotation

1. Usage

​ 1. Add spring context dependency, and spring AOP is required to use annotations, otherwise annotations cannot be used

​ 2. Add annotation to class

​ 3. Add a component scanner to the spring configuration file to explain the location of annotations in the file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--
    Declared is the component scanner, and the component is java object
    base-package Is the fully qualified name of the class
 	xmlns:context="http://www.springframework.org/schema/context"

  	 http://www.springframework.org/schema/context 					      https://www.springframework.org/schema/context/spring-context.xsd"
	Constraint file
-->
    <context:component-scan base-package="com.liyaun.ba01" />
    
    <!-- Scanners for multiple packages can be specified-->
    <context:component-scan base-package="com.liyaun.ba02" />
    <!--You can also specify a scanner to write multiple package paths";"perhaps","Split-->
    <context:component-scan base-package="com.liyaun.ba02;com.liyaun.ba01" />
    <!-- You can specify the parent package of multiple packages-->
     <context:component-scan base-package="com.liyaun" />
</beans>

2. Notes on learning

​ 1.@Component

@ Component is used to create objects, which is equivalent to the < bean > label

Attribute: value is equivalent to the id attribute in the bean, which is used to identify the unique pair created in the spring container

If the name is not specified with value, spring will create the name by itself. The default is the lowercase initial of the class name

package com.liyaun.ba01;

import org.springframework.stereotype.Component;

@Component(value = "student")
public class Student {
    private String name;
    private Integer age;
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

​ 2.@Respotory

It is used to mark the persistence layer and put it on the implementation class interface of dao layer, indicating the creation of dao objects.

​ 3.@Service

It is used to mark the service layer and put it on the implementation class of the service layer for business processing or transaction processing

​ 4.@Controller

It is used on the control layer and on the processor (controller).

​ 5.@Value

It is used to assign a value to a simple attribute of a reference class. The value attribute in @ value can be omitted and not written

Actual:

package com.liyaun.ba02;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(value = "mystudent")
public class Student {
    @Value("Fei Zhang")
    private String name;
    @Value(value = "18")
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

}

​ 6.@Autowired

The annotation injects the reference type by byType method, which is provided by the Spring framework. The automatically injected reference type can be created only if it is managed by Spring.

The @ Autowired annotation needs to add an annotation @ Qualifier(value = "bean id") in byName: it uses the object with the specified name to create a reference class object.

package com.liyaun.ba03;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(value = "mystudent")
public class Student {
    @Value("Fei Zhang")
    private String name;
    @Value(value = "18")
    private Integer age;
    @Autowired
    @Qualifier("aynu")
    private School school;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", school=" + school +
                '}';
    }
}

Attribute: the required attribute defaults to true, that is, an error will be reported when the reference type assignment fails. When it is modified to false, it will be regardless of whether the reference type is successfully injected.

​ 7.@Resource

This annotation is provided by JDK. By default, byName is used to inject the reference type. If byName is not found, byType will be used to inject.

@The last three components, @ restore, @ Service, @ Controller have the same functions as compuent, but the four are different

Because the latter three are layered, they have their own unique functions.

V AOP aspect oriented programming

1. The underlying principle is dynamic agent:

Question: what is a dynamic agent?

Dynamic proxy is to dynamically obtain the implementation interface of the enhanced class without changing the source code of the enhanced target class through reflection, and delegate it to jdk to create an object to realize the enhancement of function

Function: decouple, reduce the amount of code, and focus on business logic code

2. What is aop

AOP: its full name is aspect oriented programming

Aspect: aspect means enhanced functions, such as increased creation time, transactions, etc

3. How to understand aspect oriented programming

​ ①. It is necessary to find out the cut plane in the project analysis function

​ ②. Reasonably arrange the execution time of the section

​ ③. Reasonably arrange the execution position of the section, where and how to enhance it.

4. Terminology

​ ①. Aspect: aspect, which represents the enhanced function, that is, the code to realize the function. Non business functions,

Common facet functions include log, transaction, statistics, parameter check and permission verification.

​ ②. JoinPoint: a link point, which is the location connecting business and enhancements, that is, a business method

​ ③. Poincut: pointcut, collection of join points

​ ④. Advice: notification, indicating the execution time of the notification aspect function. Before method, after method, etc

What you need to master is:

Function code of section,

The execution position of the section uses PointCut. Biot is the execution position of the section.

Section execution time Advice

5. Implementation of AOP

aop is a technical specification, a dynamic specification and a standard.

Implementation framework of aop technology:

① spring aop: Spring implements aop internally and also uses aop when dealing with transactions

But it is rarely used in actual development because it is very clumsy

② Aspectj: an open source framework dedicated to aop. Aspectj framework is integrated into spring framework

aspectj implements aop in two ways:

​ 1. Use the xml configuration file. It is mainly used to configure transaction functions

​ 2. Use annotations for development. General development uses annotations. aspectj has five annotations

6. Use of AspectJ

​ 1. The execution time and advice of the aspect are represented by annotations in the Aspectj framework

① the @ Before attribute value is the pointcut expression, indicating the position of the pointcut

② the @ AfterReturning attribute value and returning returning returning represent the return result of the target class. If you want to use this return result to enhance the method, Li must have the same name as in returning. For example, the following are res

   @AfterReturning(value = "execution(* *..impl.*ServiceImpl.*(..))",returning = "res")
    public void timeInfor01(JoinPoint jp,Object res){

        Object[] args = jp.getArgs();
        res = (User)res;
        ((User) res).setName((String) args[0]);
        ((User) res).setAge((Integer) args[1]);
        DateUtil.getNowTime();
    }

​ ③@Around

Attribute: value can be enhanced before and after the target method,

Features: the most powerful notification.

Notifications can be executed before and after the target method

Controls whether the target method can be called

Modify execution results

There is a return value. Object is recommended

Parameter: ProceedingJoinPoint pjp is equivalent to the invoke method in InvocationHandler

//Add class
package org.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.util.DateUtil;

@Aspect
public class MyAspect {
    @Around(value = "execution(* *..service..*.*(..))")
    public Object test01(ProceedingJoinPoint pjp) throws Throwable {
        DateUtil.getNowTime();
        Object res = pjp.proceed();
        System.out.println("Transaction committed");
        res = res+"6666666666666666666666666666";
        return res;
    }
}

④ understand @ AfterThrowing

⑤ @ After understand

⑥ alias of @ PointCut execution expression

give an example:

 @Pointcut(value = "execution(* *..impl.*ServiceImpl.*(..))")
    public void name(){

    }

   @AfterReturning(value = "name()",returning = "res")
    public void timeInfor01(JoinPoint jp,Object res){

        Object[] args = jp.getArgs();
        res = (User)res;
        ((User) res).setName((String) args[0]);
        ((User) res).setAge((Integer) args[1]);
        DateUtil.getNowTime();
    }

  1. Establish maven project

  2. Introducing spring, aspectj dependency

  3. To create the target class, that is, the interface and the corresponding implementation class, all you have to do is add functions to it.

  4. Create an Aspect class and add @ Aspect annotation on the class

  5. Class, add the corresponding execution time annotation, and specify the pointcut expression execution().

  6. Create a spring configuration file and hand over the objects to spring for management. You can use annotations or xml configuration files. ① Declare the target object, ② declare the section object, ③ declare the automatic proxy generator label in aspectj.

  7. The automatic proxy generator converts the target to a proxy object. Just use the target object.

    //Interface
    package com.liyuan.service;
    
    public interface UserService {
        void doSome(String name);
    }
    
    
    //Implementation class
    package com.liyuan.service.impl;
    
    import com.liyuan.service.UserService;
    
    public class UserServiceImpl implements UserService {
        @Override
        public void doSome(String name) {
            System.out.println("How do you do   "+name);
        }
    }
    
    
    //Enhancement class
    package com.liyuan.aspect;
    
    import com.liyuan.util.DateUtil;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect//The aspect declaration is an enhanced class
    public class MyAspect {
    
        @Before(value = "execution(* com.liyuan.service.impl.*.*(..))")//Execute before method execution
        public void timeInfor(){
            DateUtil.getNowTime();
        }
    
    }
    
    
    //test
       @Test
        public void testDemo01(){
            ApplicationContext  context = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = (UserService)context.getBean("userService");
            userService.doSome("Li Yuan");
        }
    
    
    //result
    2021 09:45:52, August 8, 2008
     Hello, Li Yuan
    

    Corresponding xml configuration file

<?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 https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--    Automatic proxy generator-->
    <aop:aspectj-autoproxy />
    <!--    The automatic proxy generator represents the use of cglib Dynamic agent-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
<!--Declare target class-->
    <bean id="userService" class="com.liyuan.service.impl.UserServiceImpl"></bean>
<!--Declaration hardening class-->
    <bean id="myAspect" class="com.liyuan.aspect.MyAspect"></bean>

</beans>

7. Mastering AspectJ pointcut expression

Execution (access permission method return value method declaration (parameter) exception type)

Bold cannot be omitted.

execution (public void com.liyuan.service.UserServiceImpl.doSome(Integer,String) );

*Represents 0 to any number of characters

... represents a parameter in a method

give an example:

execution(public * * (...)) represents any public method

execution(* set * (...)) indicates any method starting with set

Execution (* com. Liyuan. Service. *. * (*...)) indicates any method in any class in the service package

Execution (* com. Liyuan. Service... *. * (...)) represents any class and method in the service and its sub packages

Execution (* *.. service... *. * (...)) indicates all methods in all classes and subclasses of the service under the multi-level package

8.@Aspect

Indicates that the current class is an aspect class, the methods in the class are enhanced methods, and the method definition requirements

① must be public

② no return value

③ there can be parameters or no parameters

If there are parameters, the parameters cannot be customized. There are several parameter types that can be used

How to obtain the execution method of the target class through JoinPoint

JoinPoint must be at the first place in the parameter list, otherwise an error will be reported!!!!!!!!!!!!

@Use of Before

@Aspect
@Component(value = "myAspects")
public class MyAspect {

    @Before(value = "execution(* *..service..*.*(..))")
    public void timeInfor(JoinPoint jp){
        System.out.println("Enhanced method signature="+jp.getSignature());
        System.out.println("Enhancement method name="+jp.getSignature().getName());
        Object[] args = jp.getArgs();
        for(Object arg:args){
            System.out.println("parameter="+arg);
        }
        DateUtil.getNowTime();
    }

}


//Operation results
 Enhanced method signature=void com.liyuan.service.UserService.doSome(String)
Enhancement method name=doSome
 parameter=Li Yuan
2021 12:36:01, August 8, 2008
 Hello, Li Yuan

@AfterReturning

//Interface package org example. service; import org. example. pojo. Student; public interface StudentService {    Student doOther(int age ,String name);}// Implementation class package org example. service. impl; import org. example. pojo. Student; import org. example. service. StudentService; Public class studentserviceimpl implements studentservice {@ override public student door (int age, string name) {student student = new student(); student.setage (18); student.setname ("Zhang San"); return student;}}// Enhancement method package org example. aspect; import org. aspectj. lang.JoinPoint; import org. aspectj. lang.annotation. AfterReturning; import org. aspectj. lang.annotation. Aspect; import org. aspectj. lang.annotation. Before; import org. example. pojo. Student; import org. example. util. DateUtil; import org. springframework. stereotype. Component;@ Aspect@Component (value = "myAspects")public class MyAspect {    @AfterReturning(value = "execution(* *..service..*.*(..))", Returning = "res") / / joinpoint must be used first, or an error will be reported! public void timeInfor(JoinPoint jp,Object res){        Object[] args = jp.getArgs();        res = (Student)res;        ((Student) res).setAge((Integer) args[0]);        ((Student) res).setName((String) args[1]);        DateUtil.getNowTime();    }}// Running results @ test public void testdemo01() {ApplicationContext context = new classpathxmlapplicationcontext ("ApplicationContext. XML"); studentservice studentservice = (studentservice) context.getbean ("studentservice"); student = studentservice.door (500, "Black Mountain demon"); system.out.println (student);} At 03:46:39 on August 8, 2021, Student{age=500, name = 'black mountain old demon'}

The use of Spring is to implement decoupling

Interface oriented programming can realize decoupling between business objects. When calling dao layer in service layer, you can choose to call to realize decoupling according to different implementations

Keywords: Spring

Added by tomm098 on Mon, 27 Dec 2021 04:30:55 +0200