spring aop 示例
***********************
示例
*****************
service 层
HelloService
public interface HelloService {
void hello();
void hello(Integer id);
void hello(String name,Integer id);
}
*****************
serviceImpl 层
HelloServiceImpl
@Service
public class HelloServiceImpl implements HelloService {
@Override
public void hello() {
System.out.println("hello 方法被调用");
}
@Override
public void hello(Integer id) {
System.out.println("hello "+ id+"被调用");
}
@Override
public void hello(String name, Integer id) {
System.out.println(name+" "+id);
}
}
*****************
aspect 层
HelloAspect
@Aspect
@Component
public class HelloAspect {
@Pointcut("execution( * *.hello())")
public void fun(){
}
@Pointcut("execution(* *.hello(Integer))&&args(id)")
public void fun2(Integer id){
}
@Pointcut(value = "execution(* *.hello(String,Integer))&&args(name,id)", argNames = "name,id")
public void fun3(String name,Integer id){
}
@Pointcut("within(com.example.demo.service.HelloService+)")
public void fun4(){
}
@Before("fun()")
public void before(){
System.out.println("前置通知");
}
@Before(value = "fun2(id)", argNames = "id")
public void before2(Integer id){
System.out.println(id);
System.out.println("前置通知2 fun2()");
}
@Before(value = "fun3(name,id)", argNames = "name,id")
public void before(String name,Integer id){
System.out.println("前置通知");
System.out.println(name+" "+id);
}
@After("fun4()")
public void after2(){
System.out.println("后置通知");
}
}
*****************
controller 层
HelloController
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/get")
public String test(){
helloService.hello();
return "success";
}
@RequestMapping("/get2")
public String test2(){
helloService.hello(2);
return "success";
}
@RequestMapping("/get3")
public String test3(){
helloService.hello("瓜田李下",23);
return "success";
}
}