Annotations仅仅是元数据,和业务逻辑无关。如果Annotations不包含业务逻辑,那么必须有人来实现这些逻辑。元数据的用户来做这个事情。Annotations仅仅提供它定义的属性(类/方法/包/域)的信息。Annotations的用户(同样是一些代码)来读取这些信息并实现必要的逻辑
以Rest请求为例
1、 建立一个注解:请求必须先登录
@Target({ ElementType.TYPE,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginValidate {
/**
* 标识被调用的类,方法是否需要登录才能访问,false:不需要登录即可访问,true:需要登录才可方法,
*
* @return
*/
booleanlogin() default true;
}</span>
2、在业务类上,使用注解
@Component
@Path("/test")
@Produces(value = MediaTypes.JSON_UTF_8)
public class TestController {
@POST
@Path("/test")
@LoginValidate
public Object test(@FormParam("passport") String passport) {
//做一些增删改查
}
}
3、 发起请求时,过滤器判断注解
@Component
public class LoginValidateRequestFilterimplements ContainerRequestFilter {
@Override
@SuppressWarnings("rawtypes")
publicvoid filter(ContainerRequestContext requestContext) throws IOException {
UriInfoui = requestContext.getUriInfo();
ResourceInfori = (ResourceInfo) ui;
Classclazz = ri.getResourceClass();
if(clazz == null) {
logger.error("RequestResourceClass not found!");
return;
}
LoginValidatevalidate = AnnotationUtils.findAnnotation(clazz, LoginValidate.class);
if(validate !=null && validate.login() == true) {
//判断是否登录
}
}
}