springmvc项目Aop自定义注解

springmvc项目Aop自定义注解

今日份敷衍
在mvc项目里写个aop自定义注解(因为没在配置文件里加入扫描跟开启aop搞了一天,简直浪费时间)
首先建两个文件如下
springmvc项目Aop自定义注解_第1张图片
一个注解,一个aop
注解是上面那个,里面怎么写呢,如下

package com.esse.project.sys.annotation;

import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CostomBasicFilter {
}

上面基本都是固定的,要是里面要传参,可以在{}里加参数
aop里这样写

//省略import
@Aspect
@Component
public class ConstomBasicFilterAop {
	@Pointcut("@annotation(com.esse.project.sys.annotation.CostomBasicFilter)")
    public void basicAuthFilter() {
        System.out.println("1");
    }

    @Before(value= "basicAuthFilter()")
    public boolean doBefore() {
     	System.out.println("2");
    }

然后在要加入注解的接口,方法上加上注解

	@CostomBasicFilter//就是这一条
    @RequestMapping("/GetTaskLists")
    @ResponseBody
    public R getTaskLists() {
        System.out.print("成功了")
        return R.ok(number);
    }

好了,我们写好了自定义注解,但还没有结束
需要在配置文件里加入扫描
spring.xml里加入
springmvc项目Aop自定义注解_第2张图片
表示扫描aop这个文件夹,把里面的类放到spring容器里进行管理
然后在spring-mvc.xml里加入
springmvc项目Aop自定义注解_第3张图片
beans的xmlns也附在下面

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

这样就可以啦
不知道要配置文件里加东西还是比较头疼的

你可能感兴趣的:(aop)