您的位置:首页 > 编程语言 > Java开发

spring中自定义注解(annotation)与AOP中获取注解

2016-04-15 00:00 585 查看
摘要: 利用spring aop 注解实现拦截方法。

一、自定义注解(annotation)
自定义注解的作用:在反射中获取注解,以取得注解修饰的类、方法或属性的相关解释。

package me.lichunlong.spring.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//自定义注解相关设置
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented

public @interface LogAnnotation {
//自定义注解的属性,default是设置默认值
String desc() default "无描述信息";
}

二、自定义注解的使用
package me.lichunlong.spring.service;

import me.lichunlong.spring.annotation.LogAnnotation;
import me.lichunlong.spring.jdbc.JdbcUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
//与其它注解一样的使用
@LogAnnotation(desc="this is UserService")
public void add() {
System.out.println("UserService add...");
}
}

三、AOP中获取注解

// 环绕通知:类似与动态代理的全过程
// 携带参数ProceedingJoinPoint,且必须有返回值,即目标方法的返回
@Around(value = "execution(* me.lichunlong.spring.service.*.*(..)) && @annotation(log)")
public Object aroundMethod(ProceedingJoinPoint pjd, LogAnnotation log) {
Object result = null;
System.out.println(log.desc());
try {
System.out.println("前置通知");
result = pjd.proceed();
System.out.println("后置通知");
} catch (Throwable e) {
System.out.println("异常通知");
}
System.out.println("返回通知");
return result;
}

四、配置扫描aop

<aop:aspectj-autoproxy proxy-target-class="true"/>

五、解决在Controller中注解不生效
一般aop扫描是配置到ApplicationContext.xml,嘿嘿,问题就在这!Spring MVC加载的WebApplicationContext而不是ApplicationContext,所以应该把schema和加载加到 spring-mvc.xml,然后?一切正常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring Controller app 注解