第一步:自定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AdminOnly {
}
第二步:创建一个切面
@Aspect
@Component
public class DemoAspect {
@Pointcut("@annotation(AdminOnly)")
public void hehe() {
}
@Before("hehe()")
public void heihei() {
System.out.println("我在执行。。。");
}
}
第三步:在对应接口上加入需要进行切入的注解
@Service
public class ProductService {
@AdminOnly
public void insert(Product product){
System.out.println("aaaa");
}
@AdminOnly
public void delete(Product Product) {
System.out.println("bbbbb");
}
}
第四步:测试一下
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
ProductServiceproductService;
@Test
public void contextLoads() {
Product product =new Product();
product.setId(1);
productService.insert(product);
}
引入jar包:
<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>