aop获取类上的注解,spring mvc aop怎么得到方法注释

1,spring mvc aop怎么得到方法注释afterReturning重写方法里面就把方法的参数,当作形参传递给arg2了public class After implements AfterReturningAdvice@Overridepublic void afterReturning(Object arg0, Method arg1, Object[] arg2,Object arg3) throws Throwable}}expression="execution(* com.uuadv.*.service..*serviceimpl.*(..))" />
2,java 获取所有带注解的类既然是基于spring,可以这样: ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver();Resource[] res = rpr.getResources("classpath*: **/*.class"); // classpath*:带*号会找jar中的class然后根据resource取clas路径就行String className = res[0].getURL().getPath();className = className.split("(classes/)|(!/)")[1];className = className.replace("/", ".").replace(".class", "");Object obj = Class.forName(className);话说我最近也在写一个这样的MVC 。。要不咱两合伙? 我写的也是基于注解,不过要支持REST风格【aop获取类上的注解,spring mvc aop怎么得到方法注释】
3,各位大神求救java 如何获取该类上字段的注解看图片我知道1.先获取这个类的classClass objclass=t.getClass();2. 获取这个类的字段属性Field[] at = objclass.getDeclaredFields();3.遍历所有字段for (Field fd : at)//比如获取这个字段上是否包含NotNullif (fd.isAnnotationPresent(NotNull.class))//这样就获取到这个注解属性了NotNull d = fd.getAnnotation(NotNull.class);}} 4.要获取一个注解,你要先获取他所在的字段希望对你有帮助!同问再看看别人怎么说的 。通过反射
4 , spring中aop全注解时配置类怎么写先说注解,使用注解配置Spring AOP总体分为两步,第一步是在xml文件中声明激活自动扫描组件功能,同时激活自动代理功能(同时在xml中添加一个UserService的普通服务层组件,来测试AOP的注解功能):<?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:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context " target="_blank" rel="nofollow noopener">http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 激活组件扫描功能,在包cn.ysh.studio.spring.aop及其子包下面自动扫描通过注解配置的组件 --><context:component-scan base-package="cn.ysh.studio.spring.aop"/><!-- 激活自动代理功能 --><aop:aspectj-autoproxy proxy-target-class="true"/><!-- 用户服务对象 --><bean id="userService" class="cn.ysh.studio.spring.aop.service.UserService" /></beans>第二步是为Aspect切面类添加注解:package cn.ysh.studio.spring.aop.aspect;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;/*** 系统服务组件Aspect切面Bean* @author Shenghany* @date 2013-5-28*///声明这是一个组件@Component//声明这是一个切面Bean@Aspectpublic class ServiceAspect private final static Log log = LogFactory.getLog(ServiceAspect.class);//配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点@Pointcut("execution(* cn.ysh.studio.spring.aop.service..*(..))")public void aspect()/** 配置前置通知,使用在方法aspect()上注册的切入点* 同时接受JoinPoint切入点对象,可以没有该参数*/@Before("aspect()")public void before(JoinPoint joinPoint)if(log.isInfoEnabled())log.info("before " + joinPoint);}}//配置后置通知,使用在方法aspect()上注册的切入点@After("aspect()")public void after(JoinPoint joinPoint)if(log.isInfoEnabled())log.info("after " + joinPoint);}}//配置环绕通知,使用在方法aspect()上注册的切入点@Around("aspect()")public void around(JoinPoint joinPoint)long start = System.currentTimeMillis();try ((ProceedingJoinPoint) joinPoint).proceed();long end = System.currentTimeMillis();if(log.isInfoEnabled())log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");}} catch (Throwable e) long end = System.currentTimeMillis();if(log.isInfoEnabled())log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());}}}//配置后置返回通知,使用在方法aspect()上注册的切入点@AfterReturning("aspect()")public void afterReturn(JoinPoint joinPoint)if(log.isInfoEnabled())log.info("afterReturn " + joinPoint);}}//配置抛出异常后通知,使用在方法aspect()上注册的切入点@AfterThrowing(pointcut="aspect()", throwing="ex")public void afterThrow(JoinPoint joinPoint, Exception ex)if(log.isInfoEnabled())log.info("afterThrow " + joinPoint + "\t" + ex.getMessage());}}}测试代码:package cn.ysh.studio.spring.aop;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.ysh.studio.spring.aop.service.UserService;import cn.ysh.studio.spring.mvc.bean.User;/*** Spring AOP测试* @author Shenghany* @date 2013-5-28*/public class Tester private final static Log log = LogFactory.getLog(Tester.class);public static void main(String[] args) //启动Spring容器ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//获取service组件UserService service = (UserService) context.getBean("userService");//以普通的方式调用UserService对象的三个方法User user = service.get(1L);service.save(user);try service.delete(1L);} catch (Exception e) if(log.isWarnEnabled())log.warn("Delete user : " + e.getMessage());}}}}控制台输出如下:INFO [spring.aop.aspect.ServiceAspect:40] before execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))INFO [spring.aop.service.UserService:19] getUser method . . .INFO [spring.aop.aspect.ServiceAspect:60] around execution(User cn.ysh.studio.spring.aop.service.UserService.get(long)) Use time : 42 ms!INFO [spring.aop.aspect.ServiceAspect:48] after execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))INFO [spring.aop.aspect.ServiceAspect:74] afterReturn execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))INFO [spring.aop.aspect.ServiceAspect:40] before execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))INFO [spring.aop.service.UserService:26] saveUser method . . .INFO [spring.aop.aspect.ServiceAspect:60] around execution(void cn.ysh.studio.spring.aop.service.UserService.save(User)) Use time : 2 ms!INFO [spring.aop.aspect.ServiceAspect:48] after execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))INFO [spring.aop.aspect.ServiceAspect:74] afterReturn execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))INFO [spring.aop.aspect.ServiceAspect:40] before execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))INFO [spring.aop.service.UserService:32] delete method . . .INFO [spring.aop.aspect.ServiceAspect:65] around execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long)) Use time : 5 ms with exception : spring aop ThrowAdvice演示INFO [spring.aop.aspect.ServiceAspect:48] after execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))INFO [spring.aop.aspect.ServiceAspect:74] afterReturn execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))WARN [studio.spring.aop.Tester:32] Delete user : Null return value from advice does not match primitive return type for: public boolean cn.ysh.studio.spring.aop.service.UserService.delete(long) throws java.lang.Exception可以看到 , 正如我们预期的那样,虽然我们并没有对UserSerivce类包括其调用方式做任何改变 , 但是Spring仍然拦截到了其中方法的调用,或许这正是AOP的魔力所在 。再简单说一下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:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context " target="_blank" rel="nofollow noopener">http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 系统服务组件的切面Bean --><bean id="serviceAspect" class="cn.ysh.studio.spring.aop.aspect.ServiceAspect"/><!-- AOP配置 --><aop:config><!-- 声明一个切面,并注入切面Bean,相当于@Aspect --><aop:aspect id="simpleAspect" ref="serviceAspect"><!-- 配置一个切入点,相当于@Pointcut --><aop:pointcut expression="execution(* cn.ysh.studio.spring.aop.service..*(..))" id="simplePointcut"/><!-- 配置通知,相当于@Before、@After、@AfterReturn、@Around、@AfterThrowing --><aop:before pointcut-ref="simplePointcut" method="before"/><aop:after pointcut-ref="simplePointcut" method="after"/><aop:after-returning pointcut-ref="simplePointcut" method="afterReturn"/><aop:after-throwing pointcut-ref="simplePointcut" method="afterThrow" throwing="ex"/></aop:aspect></aop:config></beans>个人觉得不如注解灵活和强大 , 你可以不同意这个观点,但是不知道如下的代码会不会让你的想法有所改善://配置前置通知,拦截返回值为cn.ysh.studio.spring.mvc.bean.User的方法@Before("execution(cn.ysh.studio.spring.mvc.bean.User cn.ysh.studio.spring.aop.service..*(..))")public void beforeReturnUser(JoinPoint joinPoint)if(log.isInfoEnabled())log.info("beforeReturnUser " + joinPoint);}}//配置前置通知,拦截参数为cn.ysh.studio.spring.mvc.bean.User的方法@Before("execution(* cn.ysh.studio.spring.aop.service..*(cn.ysh.studio.spring.mvc.bean.User))")public void beforeArgUser(JoinPoint joinPoint)if(log.isInfoEnabled())log.info("beforeArgUser " + joinPoint);}}//配置前置通知,拦截含有long类型参数的方法,并将参数值注入到当前方法的形参id中@Before("aspect()&&args(id)")public void beforeArgId(JoinPoint joinPoint, long id)if(log.isInfoEnabled())log.info("beforeArgId " + joinPoint + "\tID:" + id);}}附上UserService的代码(其实很简单):package cn.ysh.studio.spring.aop.service;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import cn.ysh.studio.spring.mvc.bean.User;/*** 用户服务模型* @author Shenghany* @date 2013-5-28*/public class UserService private final static Log log = LogFactory.getLog(UserService.class);public User get(long id)if(log.isInfoEnabled())log.info("getUser method . . .");}return new User();}public void save(User user)if(log.isInfoEnabled())log.info("saveUser method . . .");}}public boolean delete(long id) throws Exceptionif(log.isInfoEnabled())log.info("delete method . . .");throw new Exception("spring aop ThrowAdvice演示");}return false;}}应该说学习Spring AOP有两个难点,第一点在于理解AOP的理念和相关概念,第二点在于灵活掌握和使用切入点表达式 。概念的理解通常不在一朝一夕 , 慢慢浸泡的时间长了,自然就明白了,下面我们简单地介绍一下切入点表达式的配置规则吧 。通常情况下,表达式中使用”execution“就可以满足大部分的要求 。表达式格式如下:execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) modifiers-pattern:方法的操作权限ret-type-pattern:返回值declaring-type-pattern:方法所在的包name-pattern:方法名parm-pattern:参数名throws-pattern:异常其中,除ret-type-pattern和name-pattern之外,其他都是可选的 。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值为任意类型;方法名任意;参数不作限制的所有方法 。最后说一下通知参数可以通过args来绑定参数,这样就可以在通知(Advice)中访问具体参数了 。例如,<aop:aspect>配置如下:<aop:config><aop:aspect id="TestAspect" ref="aspectBean"><aop:pointcut id="businessService"expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" /><aop:after pointcut-ref="businessService" method="doAfter"/></aop:aspect></aop:config>上面的代码args(msg,..)是指将切入点方法上的第一个String类型参数添加到参数名为msg的通知的入参上,这样就可以直接使用该参数啦 。5,请问 java 怎么获取一个类里面属性上方的注释类运行的时候是编译过的字节码 。字节码中注释是没有的 。我去 。这个javabean对象中的注释,是方便其他程序员对该属性的理解才写的这是一种开发规范,只是用于让其他新人队该属性的作用了解 , 注释注释,他就是注释我去 。只能在javadoc中看 , java编译的时候会去掉注释的 。建议你看看javadoc的用法 。希望对你有所帮助 。可能被获取的 。。。除非你写民@XXXX所谓注释,就是编译的时候不鸟他 , 所以编译之后的class文件是没有注释的 , 所以你会发现eclipse引入的jar包,把鼠标放上去,如果不自己设置jar包的源码路径,是不会看到注释的~你这需求不可能实现,如果有源码,倒是可以把 , 毕竟eclipse已经有这个功能了6,Spring aop 注解方式怎么获得执行了目标的某个方法private void beforeTransationHandle(JoinPoint point) throws Exception//拦截的实体类Object target = point.getTarget();//拦截的方法名称String methodName = point.getSignature().getName();//拦截的方法参数Object[] args = point.getArgs();//拦截的放参数类型Class[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();Method m = null;try//通过反射获得拦截的methodm = target.getClass().getMethod(methodName, parameterTypes);//如果是桥则要获得实际拦截的methodif(m.isBridge())for(int i = 0; i < args.length; i++)//获得泛型类型Class genClazz = GenericsUtils.getSuperClassGenricType(target.getClass());//根据实际参数类型替换parameterType中的类型if(args[i].getClass().isAssignableFrom(genClazz))parameterTypes[i] = genClazz;}}//获得parameterType参数类型的方法m = target.getClass().getMethod(methodName, parameterTypes);}} catch (SecurityException e)e.printStackTrace();} catch (NoSuchMethodException e)e.printStackTrace();}}7,java 获取所有带注解的类把打包后的jar文件与spring注解依赖jar包放在同一个JVM下运行(就是运行时能在classpath找到那些注解的相关类)应该没有问题的!还有就是要保证编译和运行的jdk版本相同既然是基于spring,可以这样: ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver();Resource[] res = rpr.getResources("classpath*: **/*.class"); // classpath*:带*号会找jar中的class然后根据resource取clas路径就行String className = res[0].getURL().getPath();className = className.split("(classes/)|(!/)")[1];className = className.replace("/", ".").replace(".class", "");Object obj = Class.forName(className);话说我最近也在写一个这样的MVC 。。要不咱两合伙? 我写的也是基于注解,不过要支持REST风格要获取jar包中的.class文件...不可以使用getResource()类似的方法...要使用JarFile这个类.来解析你的jar文件.才可以读取jar中的class.具体做法见API吧,路子是这个.你这种思想是错误的 , 类需要被使用才会被加载到内存中,其他的都是没有加载的,那你也找不到 。你要是全部加载,那对jvm的性能来说是白白浪费了 。要实现你这种需求非常简单 直接给需要的类一个自定义的注解 ,使用aop,在前置通知的地方去做你现在的需求就ok@retention(retentionpolicy.runtime) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到@target(@documented//说明该注解将被包含在javadoc中public @interface fieldmeta /*** 是否为序列号* @return*/boolean id() default false;/*** 字段名称* @return*/string name() default "";/*** 是否可编辑* @return*/boolean editable() default true;/**1. 首先取得classpath的绝对路径如:SpringTest.class.getClass().getResource("/").getPath();2. 递归遍历该路径下的文件夹,直到判定是文件就将该文件class.forname加载到List中3. 遍历List,根据你的注解来构造你的map ...... 不明白再问.......

    推荐阅读