Spring

2022-11-27  本文已影响0人  请叫我平爷

v# Spring

简介

IOC、DI

@Scope、@PostConstruct、@PreDestory

@Mapper、@Repository

SpringIOC容器

Spring提供了两种IOC容器

AOP Aspect Oriented Programming

面向切面编程:将涉及多业务流程的通用功能抽取并单独封装,形成独立的切面,在合适的时机将这些切面横向切入到业务流程指定的位置中

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

AopMethod

@Component
public class AopMethod {

    public int add (int a , int b){
        System.out.println("AopMethod add start "+a+" "+b);
        int res = a+b;
        System.out.println("AopMethod end "+res);

        return res;
    }
}

MyAopAspect

@Aspect
@Component
public class MyAopAspect {

    @Pointcut("execution(* com.mi.learn.aspect.demo.component.AopMethod.*(..))")
    public void pointCut() {}

    @Before("pointCut()")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("MyAopAspect.beforeMethod");
    }

    @After("pointCut()")
    public void afterMethod(){
        System.out.println("MyAopAspect.afterMethod");
    }


    @AfterReturning(value = "pointCut()",returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint,Object result){
        System.out.println("MyAopAspect.afterReturningMethod");
    }

    @AfterThrowing(value = "pointCut()",throwing = "e")
    public void afterThrowingMethod(JoinPoint joinPoint,Exception e){
        System.out.println("MyAopAspect.afterThrowingMethod");
    }

    @Around("pointCut()")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){

        System.out.println("MyAopAspect.aroundMethod-1 ");
        Object object = null;
        try {
            object = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("MyAopAspect.aroundMethod-2 object" + object);
        return object;
    }
}

Test

@Test
public void testMethod(){
  int res = method.add(1,4);
  System.out.println("res-->"+res);
}

log日志

MyAopAspect.aroundMethod-1 
MyAopAspect.beforeMethod
AopMethod add start 1 4
AopMethod end 5
MyAopAspect.afterReturningMethod
MyAopAspect.afterMethod
MyAopAspect.aroundMethod-2 object 5
res-->5

事务

Transactional

上一篇 下一篇

猜你喜欢

热点阅读