首页 > 解决方案 > 如何使用自定义注释中的参数调用注释?

问题描述

如何使用触发另一个注释(例如@Bean(parameterFromCustomAnnotation))的参数创建@CustomAnnotation?

这甚至可能吗?

@Bean # How to add a parameter from the MyBean annotation to @Bean?
@Transactional(rollbackFor = Exception.class, timeout = 5)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyBean{}

标签: springannotations

解决方案


在下面找到示例:

第一步:创建您的自定义注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DummyService
{
    APIServiceName serviceName() ;
}

第二步:创建参数

 public enum APIServiceName
{
    ADD_USER,
    GET_USER_BY_ID
}

第三步:为 API 使用您的自定义注释

 @DummyService(serviceName = APIServiceName.ADD_USER)
    @RequestMapping(value = /addUSer, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody dummyResponse addUserToDB(@RequestBody String userReq, HttpServletRequest request) {
  logic goes here
}

推荐阅读