在SpringBoot中使用AOP切面编程

若是有对SpringAOP不太懂的小伙伴能够查看我以前的Spring学习系列博客 SpringBoot的出现,大大地下降了开发者使用Spring的门槛,咱们再也不须要去作更多的配置,而是关注于咱们的业务代码自己,在SpringBoot中使用AOP有两种方式:html

1、使用原生的SpringAOP(不是很推荐,但这是最基本的应用)

第1步,引入Aspect的相关依赖

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.1</version>
        </dependency>
	<!--织入器-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.1</version>
        </dependency>

第二步,在SpringBoot的配置类中开启AspectJ代理

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringbootLearnApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootLearnApplication.class, args);
	}

}

第三步,写代码

  • 建立一个目标类
/**
 * 教师类
 */
@Component
public class HighTeacher {
    private String name;
    private int age;

    public void teach(String content) {
        System.out.println("I am a teacher,and my age is " + age);
        System.out.println("开始上课");
        System.out.println(content);
        System.out.println("下课");
    }

    ...getter and setter
}
  • 切面类,用来配置切入点和通知
/**
 * 切面类,用来写切入点和通知方法
 */
@Component
@Aspect
public class AdvisorBean {
    /*
    切入点
     */
    @Pointcut("execution(* teach*(..))")
    public void teachExecution() {
    }

    /************如下是配置通知类型,能够是多个************/
    @Before("teachExecution()")
    public void beforeAdvice(ProceedingJoinPoint joinPoint) {
       Object[] args = joinPoint.getArgs();
        args[0] = ".....大家体育老师生病了,咱们开始上英语课";
        Object proceed = joinPoint.proceed(args);
        
        return proceed;
    }
}
  • 测试类
package cn.lyn4ever.learn.springbootlearn;

import cn.lyn4ever.learn.springbootlearn.teacher.HighTeacher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = SpringbootLearnApplication.class)
@RunWith(SpringRunner.class)
public class SpringbootLearnApplicationTests {

    @Autowired
    HighTeacher highTeacher;

	@Test
	public void contextLoads() {
        highTeacher.setAge(12);
        highTeacher.teach("你们好,咱们你们的体育老师,咱们开始上体育课");
	}
}

结果就是你们想要的,体育课被改为了英语课 结果就是你们想要的,体育课被改为了英语课java

2、使用Springboot-start-aop(推荐)

在pom文件中引入web

<dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-aop</artifactId>  
        </dependency>
  • 这一个依赖,就是将多个aop依赖整合到一块儿,咱们只须要关注代码的编写

小鱼与Java

相关文章
相关标签/搜索