Introduction to Spring-IOC and AOP

Introduction to Spring-IOC and AOP

1. Import Spring dependency

     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>5.2.4.RELEASE</version>
     </dependency>

2. Use of IOC

2.1 profile implementation dependency injection

2.1.1 coding

  1. userService and userServiceImpl
package com.luogs.service;

import com.luogs.pojo.User;

    public interface UserService {

    User getUserById(int id);
}
package com.luogs.service;

import com.luogs.dao.UserDao;
import com.luogs.pojo.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserServiceImpl implements UserService {

    private UserDao userDao;//This variable is given to Spring for injection

    public User getUserById(int id) {
        return userDao.getUserById(id);

    }
}

  1. userDao and userDaoImpl
   package com.luogs.dao;
   
   import com.luogs.pojo.User;
   
   public interface UserDao {
   
           User getUserById(int id);
   
   
   }
package com.luogs.dao;

import com.luogs.pojo.User;

public class UserDaoImpl implements UserDao {

    private User user;//This variable is given to Spring for injection

    public User getUserById(int id) {
        System.out.println("Find a user!");
        user.setId(id);
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

  1. user entity class
 package com.luogs.pojo;

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

@ToString
public class User {

    private int id;
    private String name;
    private int age;
    private  String gender;

    public void setId(int id) {
        this.id = id;
    }

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

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

    public void setGender(String gender) {
        this.gender = gender;
    }
}

2.1.2 preparation of configuration file

  1. applicationContext.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">
   
       <import resource="beans.xml"/>
       <bean id="user"  class="com.luogs.pojo.User">
           <property name="id" value="1" />
           <property name="name" value="logs"/>
           <property name="age" value="32" />
           <property name="gender" value="male"/>
       </bean>
   </beans>
  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:scemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   
       <bean id="userDao" class="com.luogs.dao.UserDaoImpl" autowire="byName">
          <!-- <property name="user"  ref="user"></property>-->
       </bean>
       <bean id="userService" class="com.luogs.service.UserServiceImpl" autowire="byType">
          <!-- <property name="userDao" ref="userDao"></property>-->
       </bean>
   </beans>

2.1.3 test

import com.luogs.pojo.User;
import com.luogs.service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DaoTest {

    @Test
    public void  fTest(){
        //1. Read configuration information
        ClassPathXmlApplicationContext config = 
        new ClassPathXmlApplicationContext("applicationContext.xml");
        //2. Get the configured bean
        //<bean id="userService" class="com.luogs.service.UserServiceImpl" autowire="byType">
        UserService userService = config.getBean("userService", UserService.class);
        //3. Use the obtained bean to test whether it is successful
        User user = userService.getUserById(11);
        System.out.println(user);
    }
}

2.1.4 description

  1. Read the configuration file through ClassPathXmlApplicationContext
  2. Get the interface class of the corresponding bean (UserService) through the getBean() method
  3. The userDao attribute of userService is assigned by automatic assembly
  4. The attribute user of userDao is assigned through automatic assembly
  5. Execute method call getUserbyId(11) through Userservice interface class

2.2 annotation implementation dependency injection

2.2.1 open comment

<?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">

    <context:annotation-config/>
</beans>

2.2.2 annotation scanning package

<context:component-scan base-package="com.luogs.*"/>

Only scan scope annotations are controlled by Spring, that is, to be created by Spring

2.2.3 common notes

  1. **@Component**:Spring component, controlled by Spring
  • @Service

  • @Repository

    • @Controller
    1. @Autowired: auto assemble

    2.2.4 example code - sevice Dao POJO

    import com.luogs.dao.StudentDao;
    import com.luogs.pojo.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class QueryStudentServiceImpl implements QueryStudentService {
    
        public void setStudentDao(StudentDao studentDao) {
            this.studentDao = studentDao;
        }
    
        @Autowired
        private StudentDao studentDao;
    
        @Override
        public Student query() {
    
            return studentDao.queryStudent();
        }
    }
    
    import com.luogs.pojo.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class StudentDaoImpl implements StudentDao {
    
        @Autowired
        private Student stu;
    
        @Override
        public Student queryStudent() {
            return stu;
        }
    }
    
    import lombok.ToString;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    @ToString
    public class Student {
    
        @Value("Xiao Ming")
        private String name;
    
        @Value("11")
        private String age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    }
    

    2.3 IOC summary

    1. The way Spring implements IOC is dependency injection (DI)

    2. applicationContet.xml can be named at will, mainly for configuration bean s, which are created by Spring and automatically assembled by autowire = "byName" (or byType)

    3. Use annotation steps:

      • Introduce constraint context
      • Enable annotation configuration
      • Open scan package
      • Start using annotation development
    4. You can also use the @ Configuration annotation to use Java as a Configuration class

    3. Use of AOP

    3.1 import dependency weaving package

    <dependency>-
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.5</version>
    </dependency>
    

    3.2 profile inheritance interface implementation

    1. Preamplifier
    import org.springframework.aop.MethodBeforeAdvice;
    import org.springframework.stereotype.Component;
    import java.lang.reflect.Method;
    
    @Component
    public class BeforeLog implements MethodBeforeAdvice {
    
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println("Pre log!!!");
        }
    }
    
    
    1. Return enhancement
    import org.springframework.aop.AfterReturningAdvice;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.stereotype.Component;
    
    import java.lang.reflect.Method;
    
    @Component
    public class AfterLog implements AfterReturningAdvice {
    
        @Override
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("Post log!!!");
        }
    }
    
    1. Access point
    package com.luogs.service;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceImpl implements UserService {
    
    
    
    
        public void getUser() {
            System.out.println("Get a user information");
        }
    
        public void addUser() {
    
            System.out.println("New user!!");
        }
    }
    
    
    1. Core profile - define pointcuts, connect access points and enhancements
    <?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"
           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/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.luogs"/>
    
    
        <aop:config>
            <aop:pointcut id="pointcut" expression="execution(* com.luogs.service.UserService.*(..))"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        </aop:config>
    
    
    </beans>
    
    • aop:pointcut pointcut definition
    • aop:advisor enhanced definition

    3.3 configuration file - Implementation of custom class

    1. Facet - contains custom advice
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.springframework.stereotype.Component;
    
    @Component
    public class AllLog {
    
        public void beforeLog()
        {
            System.out.println("Preamplifier");
        }
    
        public void afterLog()
        {
            System.out.println("Post enhancement");
        }
    
        public void aroundLog(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("Surround enhancement 1");
    
            joinPoint.proceed();
    
            System.out.println("Surround enhancement 2");
        }
    }
    
    
    2. Access point - enhanced method
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceImpl implements UserService {
    
    
        public void getUser() {
            System.out.println("Get a user information");
        }
    
        public void addUser() {
    
            System.out.println("New user!!");
        }
    }
    
    3. Profile - connection facets and access points - define pointcuts
    
    <aop:config>
        <aop:aspect ref="allLog">
            <aop:pointcut id="pointcut" expression="execution(* com.luogs.service.UserService.*(..))"/>
            <aop:before method="beforeLog" pointcut-ref="pointcut"/>
            <aop:after method="afterLog" pointcut-ref="pointcut"/>
            <aop:around method="aroundLog" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>
    
    

    3.4 notes - aspectj

    3.4.1 add annotation support

    <aop:aspectj-autoproxy/>
    

    3.4.2 write tangent class - @ Aspect annotation

    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component//Give this class to Spring
    public class AnnotationLog {
    
    
       @Before(value = "execution(* com.luogs.service.UserService.*(..))")
       public void before(){
    
           System.out.println("@@@@@@@@@@@@@@Annotation log pre enhancement@@@@@@@@@@@@@");
       }
        @After(value="execution(* com.luogs.service.UserService.*(..))")
        public void after(){
    
            System.out.println("@@@@@@@@@@@@@@Annotation log post enhancement@@@@@@@@@@@@@");
        }
    
        @Around(value = "execution(* com.luogs.service.UserService.*(..))")
        public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    
            System.out.println("@@@@@@@@@@@@@@Annotation log wrapping enhancement 1@@@@@@@@@@@@@");
            joinPoint.proceed();
            System.out.println("@@@@@@@@@@@@@@Annotation log wrapping enhancement 2@@@@@@@@@@@@@");
        }
    
        @AfterReturning(value="execution(* com.luogs.service.UserService.*(..))")
        public void afterReturn()
        {
            System.out.println("afterReturn");
        }
    }
    

3.5 test-

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class UserServiceImplTest {

    @Test
    public void getUser() {
        ClassPathXmlApplicationContext ac = 
        new ClassPathXmlApplicationContext("aopContext.xml");
        UserService uservice = ac.getBean(UserService.class);
        uservice.getUser();
        System.out.println("-----------------------------");
        uservice.addUser();
    }
}

3.6 AOP summary

  1. Aop is to execute some programs before, after and around a method

  2. Defining this method range is called pointcut. For example, all methods of all classes under a package, or all methods called save(), etc

  3. The selected method is called join point

  4. And these programs are called advice

  5. The first implementation is to write Advice in java. In the configuration file, associate all Advice, Pointcut and JoinPoint together. The disadvantage is that each Advice has to write a class that implements the interface

  6. The second kind of custom aspect is a class that contains all Advice. After defining the aspect, you can associate the Advice, PointCut and JoinPoint in the aspect with the configuration file

  7. The so-called association is that some methods (JoinPoint) are selected, which execute some programs around the front and back of the method; and the selected rule is called pointCut

  8. The third way is to use annotations. Logically, it is the same as the second way. It uses @ Aspect annotation to identify facets, uses @ Before annotation to identify Advice, and uses the annotation parameter execution() to define entry points and associate access points

Published 1 original article, praised 0, visited 9
Private letter follow

Tags: Spring xml Lombok encoding

Posted on Sun, 15 Mar 2020 00:58:37 -0400 by ORiGIN