spring aop 示例

本文通过一个详细的示例,介绍了如何在 Spring 框架中使用 AOP(面向切面编程)来增强服务层的方法,包括前置通知、后置通知等特性,展示了 AOP 在实际开发中的应用。

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";
    }
}

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值