在SpringBoot中使用AOP切面編程


如果有對SpringAOP不太懂的小伙伴可以查看我之前的Spring學習系列博客
SpringBoot的出現,大大地降低了開發者使用Spring的門檻,我們不再需要去做更多的配置,而是關注於我們的業務代碼本身,在SpringBoot中使用AOP有兩種方式:

一、使用原生的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("大家好,我們大家的體育老師,我們開始上體育課");
	}
}

結果就是大家想要的,體育課被改成了英語課
結果就是大家想要的,體育課被改成了英語課

二、使用Springboot-start-aop(推薦)

在pom文件中引入

	<dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-aop</artifactId>  
        </dependency> 
  • 這一個依賴,就是將多個aop依賴整合到一起,我們只需要關注代碼的編寫

小魚與Java


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM