【实例展示】对AOP编程的理解(二)

上一篇中定义切点的“不限”部分作出解释

 定义切点时有一些参数的不限制的。

@Pointcut(value = "execution( * com.hsf.spring.aop.controller.*.*(..))")

以上一篇中的controller为例。若要让切点识别hello2,可以将注解补充完整:

@Pointcut(value = 
"execution( String com.hsf.spring.aop.controller.HelloController.hello2(String))")

路径中两个星号变成了指定的方法的路径,比起之前指定到包的层面,进一步指定HelloController类的hello2方法。首位两端多出了两个String意义不同。第一个String指需要目标方法的返回值是String。第二个String指目标方法的传入参数必须是String。hello2满足入参和返回值都是String,所以能够被切点识别,调用通知。


以上对切点的设置若不符合hello2,则通知不会启动,且控制台报错

2021-06-15 11:41:58.773  INFO 143396 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-06-15 11:41:58.773  INFO 143396 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-06-15 11:41:58.774  INFO 143396 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms

这个错误也会出现在未定义Controller的情况中。在Controller类上加@RestController注解即可。

这个报错的原因就是切点没有找到合适的目标方法,无论是没有Controller还是在Controller中找不到符合条件的方法。


在Controller类中加入多个方法来测试切点对指定方法的识别。 

@RestController
public class HelloController {

    @GetMapping("/hello1")
    //访问localhost:8080/hello1?str=hsf时将会把调用方法hello11并将参数str通过@RequestParam("name")传给String name
    public String hello11(@RequestParam("str") String name){
        return "hello1 :"+ name;
    }

    @GetMapping("/hello2")
    //访问localhost:8080/hello2?inte=1时将会把调用方法hello22并将参数inte通过@RequestParam("int")传给int num
    public String hello22(@RequestParam("inte") int num){
        return "hello2 :"+ num;
    }

    @GetMapping("/hello3")
    //访问localhost:8080/hello3?str=hsf&inte=1时将会把调用方法hello33并传递两个参数
    public String hello33(@RequestParam("str") String name, @RequestParam("inte") int num){
        return "hello3 :"+ name + num;
    }

    @GetMapping("/hello4")
    //访问localhost:8080/hello4?inte=1时将会把调用方法hello22并将参数str通过@RequestParam("str")String str,此时参数1是字符串。
    public String hello44(@RequestParam("str") String str){
        return "hello4 :"+ str;
    }
}

分别访问四个URL均可以获得界面确保Controller正常运行。在切点中加入一些限制,如

@Pointcut(value = "execution( * com.hsf.spring.aop.controller.*.*(String))")

规定了传入的参数有且只有一个字符串,则hello1和hello4可以调用通知,而hello2因为参数是int,hello3因为有不止一个参数所以不会调动通知。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值