gpt4 book ai didi

spring-boot - 使用 BeanPostProcessor 在 Spring 中自定义注解

转载 作者:行者123 更新时间:2023-12-04 20:57:09 25 4
gpt4 key购买 nike

我们正在尝试在 Spring 中为我们的 rest api 创建一个自定义注释。我是创建自定义注释的新手,我在下面给出了代码片段

Spring Boot 应用程序 --

@SpringBootApplication
@ComponentScan(basePackageClasses = {ServiceController.class, CustomAnnotatorProcessor.class})
public class ServiceApp {
public static void main(String[] args) {
SpringApplication.run(ServiceApp.class, args);
}
}

休息 Controller --

@RestController
public class ServiceController {

@RequestMapping(method = RequestMethod.GET, value="/service/v1/version")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = String.class),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
@CustomAnnotation()
public String getVersion() {
return "success";
}
}

自定义注释 --

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface CustomAnnotation {

}

注解处理器--

@Component
public class CustomAnnotatorProcessor implements BeanPostProcessor {

private ConfigurableListableBeanFactory configurableBeanFactory;

@Autowired
public CustomAnnotatorProcessor(ConfigurableListableBeanFactory beanFactory) {
this.configurableBeanFactory = beanFactory;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
MethodCallback methodCallback = new CustomAnnotationMethodCallback(configurableBeanFactory, bean);
ReflectionUtils.doWithMethods(bean.getClass(), methodCallback);
return bean;
}

方法回调--

public class CustomAnnotationMethodCallback implements MethodCallback{
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (method.isAnnotationPresent(CustomAnnotation.class)) {
System.out.println("doWith is getting called for CustomAnnotationMethodCallback");
ReflectionUtils.makeAccessible(method);
//DO VALIDATION WHETHER A SPECIFIC HEADER IS PRESENT IN THE GIVEN REQUEST
return;
}
}

}

我正在尝试在实现 BeanPostProcessor 的类中处理自定义注释,但我遇到了问题

问题_1:回调被调用一次,但我无法对进入/service/v1/version API 的每个请求应用验证。我需要验证每个请求,我们的设计/方法是否正确,如果正确如何解决这个问题,如果不正确,请提出不同的方法

问题_2:如果我需要将完整的请求对象(与 header 一起)传递到我的@customAnnotation,我应该怎么做?

如果您需要更多详细信息,请告诉我

谢谢

最佳答案

为了处理自定义注释@validateAuthentication,我们创建了扩展HandlerInterceptorAdapter 的拦截器类。

我们在 preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 方法中实现请求 header 的验证。

关于spring-boot - 使用 BeanPostProcessor 在 Spring 中自定义注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com