spring自定义注解及aop中获取注解的值

自定义注解:

package aop;

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 MyAnnotation {
	/**
	 * 测试自定义注释
	 * @return
	 */
	String method() default "";
}

aop目标类:

package aop;

public class Target {
	/**
	 * 存储方法
	 */
	@MyAnnotation(method = "测试注解")
	public void save() {
		System.out.println("save方法执行");
	}
}

aop通知类:

package aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/*该类时通知类*/
@Aspect
public class Myadvice {
	/**
	 * 声明切入点
	 */
	@Pointcut(value = "execution(* aop.Target.save(..))")
	public void pc() {
	}

	/**
	 * 环绕通知
	 * 
	 * @throws Throwable
	 */
	@Around("Myadvice.pc()&&@annotation(mytest)")
	public Object aroundMethod(ProceedingJoinPoint pjp, MyAnnotation mytest) throws Throwable {
		System.out.println("环绕通知前*********************");
		System.out.println(mytest.method() + "*********************8");
		Object tagert = pjp.proceed();
		System.out.println("环绕通知后*********************");
		return tagert;
	}

}

测试类:

package aop;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:applicationContext.xml")
public class test {
	@Resource(name="daoImpl")
	Target dao;
	
	@Test
	public void saveTest() {		
		dao.save();
	}
}

applicationContest.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
	<!-- 1.配置目标对象 -->
	<bean id="daoImpl" class="aop.Target" />
	<!-- 2.配置通知对象 -->
	<bean id="myaspectj" class="aop.Myadvice" />
	<!-- 3.开启使用注解完成织入 -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

参考:https://blog.csdn.net/qpfjalzm123/article/details/45061701

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值