本自定義注解的作用:用於控制類方法的調用,只有擁有某個角色時才能調用。
java內置注解
1、@Target 表示該注解用於什么地方,可能的 ElemenetType 參數包括:
ElemenetType.CONSTRUCTOR 構造器聲明
ElemenetType.FIELD 域聲明(包括 enum 實例)
ElemenetType.LOCAL_VARIABLE 局部變量聲明
ElemenetType.METHOD 方法聲明
ElemenetType.PACKAGE 包聲明
ElemenetType.PARAMETER 參數聲明
ElemenetType.TYPE 類,接口(包括注解類型)或enum聲明
2、@Retention 表示在什么級別保存該注解信息。可選的 RetentionPolicy 參數包括:
RetentionPolicy.SOURCE 注解將被編譯器丟棄
RetentionPolicy.CLASS 注解在class文件中可用,但會被VM丟棄
RetentionPolicy.RUNTIME VM將在運行期也保留注釋,因此可以通過反射機制讀取注解的信息。
一、注解類源碼
/** * 方法訪問角色注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface VisitorRole { String value(); }
二、Person類的源碼。該類使用了自定義注解。
@Component("person") //此處通過注解的方式定義受管Bean public class Person { private String userId = "cjm"; private String userName = "jumin.chen"; @VisitorRole("ADMIN") //自定義注解的使用。只有具有ADMIN角色才能調用本方法。 public String say(){ return "I'm " + userName; } }
三、通過環繞通知對方法進行攔截,只有當角色匹配時,才能執行方法。
/** * 環繞通知:在類方法調用前,先判斷角色是否匹配。 */ @Component("visitorRoleAdvice") public class VisitorRoleAdvice implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { if(invocation.getMethod().isAnnotationPresent(VisitorRole.class)){ //有指定注解 String role = null; Annotation annotation = invocation.getMethod().getAnnotation(VisitorRole.class); //獲取指定注解 if(annotation!=null){ role = ((VisitorRole)annotation).value(); //從注解中獲取角色 } if("ADMIN".equals(role)){ return invocation.proceed(); //角色匹配,繼續執行方法 }else{ System.out.println("沒有角色權限!"); return null; } }else{ //類方法沒有自定義注解,直接執行該方法 return invocation.proceed(); } } }
四、Spring配置
<!-- 聲明通過注解定義bean,同時也通過注解自動注入 --> <context:component-scan base-package="com.cjm" annotation-config="true"/> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/> <bean id="nameMatchMethodPointcutAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"> <property name="advice" ref="visitorRoleAdvice"/> <property name="mappedNames"> <list> <value>say</value> </list> </property> </bean>