SSM自定义注解
时间: 2023-07-23 16:05:07 浏览: 53
在SSM中,我们可以通过自定义注解来简化开发,提高代码的可读性和可维护性。下面是一个自定义注解的示例:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "";
}
```
上述代码中,我们定义了一个名为"MyAnnotation"的注解,并指定了它的生命周期为运行时。该注解只能用于方法上,同时还有一个默认值为""的属性"value"。
接下来,我们可以在需要使用该注解的方法上添加该注解,并设置"value"属性的值,如下所示:
```java
@MyAnnotation(value = "test")
public void testMethod() {
// do something
}
```
在运行时,我们可以通过反射获取该方法上的注解信息,并根据注解信息进行相应的处理,如下所示:
```java
Method method = obj.getClass().getMethod("testMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
if (annotation != null) {
String value = annotation.value();
// do something with value
}
```