1、自定義注解Car_color
package com.dist.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //@Target(ElementType.PARAMETER) //表示這個注解的只適用於屬性,也可以寫多個({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) //表示注解只在執行期起作用 public @interface Car_color { //返回值String就是參數的類型,只能是基本類型 //這里用default默認參數是“白色” String color() default "白色"; //color方法其實是聲明了一個配置參數 }
2、將注解帶到類或接口或字段或方法上
//@Car_color(color="黑色") public class Car { @Car_color(color="黑色") private String color; }
3、獲取方法
1)類上注解獲取值
public class Test { public static void main(String[] args) throws ClassNotFoundException { Class cls=Class.forName("com.dist.annotation.Car"); //獲取類對象 Car_color annotation = (Car_color) cls.getAnnotation(Car_color.class); System.out.println(annotation.color()); } }
2)獲取字段上的
public class Test { public static void main(String[] args) throws ClassNotFoundException { Class cls=Class.forName("com.dist.annotation.Car"); //獲取類對象 Field[] field=cls.getDeclaredFields(); //獲取類的屬性數組 for(Field f:field){ //循環屬性 if(f.isAnnotationPresent(Car_color.class)){ //獲取屬性的注解,並判斷是否是Car_color.class注解 Car_color car=f.getAnnotation(Car_color.class); //獲取Car_color注解對象 System.out.println("汽車顏色:"+car.color()); //輸出注解的color配置參數 } } } }
Spring MVC實現獲取
@Controller @RequestMapping("/test") public class testApp { //請求映射處理映射器 //Spring MVC 在啟動的時候將所有貼有@RequestMapping注解的請求,收集起來,封裝到該對象中 @Autowired private RequestMappingHandlerMapping rmhm; @RequestMapping("/testann") public String testAnn(){ /** * Spring獲取注解的內容: * 1.先要獲取控制器方法(可以通過請求映射處理映射器獲取方法上的@RequestMapping) * 2.遍歷方法,可以獲取其注解值 */ //1.獲取controller中所有帶有@RequestMapping標簽的方法 Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods(); Collection<HandlerMethod> methods = handlerMethods.values();//獲得所有方法 for (HandlerMethod method:methods){ System.out.println(method); //2.遍歷所有方法,獲得方法上的指定備注值 Car_color annotation = method.getMethodAnnotation(Car_color.class); if(annotation != null){ String resource = annotation.color(); } } return null; } }
如果上面的 rmhm變量:
RequestMappingHandlerMapping 找不到,報錯誤 Could not autowire. No beans of 'RequestMappingHandlerMapping' type found
那在spring-mvc.xml文件配置這個bean (如果是spring boot 看我下下一篇文章:https://www.cnblogs.com/fps2tao/p/13677544.html)
<bean id="requestMappingHandlerMapping" class="org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping"> </bean>
轉 : https://www.cnblogs.com/x54256/p/9429815.html