若是有對SpringAOP不太懂的小夥伴能夠查看我以前的Spring學習系列博客 SpringBoot的出現,大大地下降了開發者使用Spring的門檻,咱們再也不須要去作更多的配置,而是關注於咱們的業務代碼自己,在SpringBoot中使用AOP有兩種方式:html
<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>
@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
在pom文件中引入web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>