SpringBoot使用注解AOP
项目依赖:使用sop要用到aop的起步依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
切面:
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(AdminOnly)")
public void adminOnly(){
}
@Before("adminOnly()")
public void check(){
System.out.println("before====");
}
}
注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AdminOnly {
}
接口实现上的注解:
@Service
public class TestServiceImpl implements TestService {
@AdminOnly
@Override
public void addUser() {
System.out.println("add a User");
}
@Override
public void updateUser() {
System.out.println("update a User");
}
}
测试:主要在方法上注解了 @AdminOnly的方法才会被拦截。
@Test
public void contextLoads() {
testService.addUser();
testService.updateUser();
}