我将尝试在这里更详细地描述有关Spring中自定义注释和处理器的内容。
我不知道你想要什么或需要什么,但我会给出一个通用的例子。
你有两个选择:
BeanProcessor
HandlerInterceptor
BeanProcessor
你基本上需要构建三件事:注释、BeanProcessor和回调函数,以执行你的逻辑(如果进行了注释)。以下是一个示例及其工作原理:
1-创建注释
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Documented
public @interface Reactive {
Integer ttlRequest;
}
2 - 实现一个BeanPostProcessor
@Component
public class ReactiveAnnotationProcessor implements BeanPostProcessor {
private ConfigurableListableBeanFactory configurableBeanFactory;
@Autowired
public ReactiveAnnotationProcessor(ConfigurableListableBeanFactory beanFactory) {
this.configurableBeanFactory = beanFactory;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
this.scanReactiveAnnotation(bean, beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
protected void scanReactiveAnnotation(Object bean, String beanName) {
this.configureMethodInjection(bean);
}
private void configureMethodInjection(Object bean) {
Class<?> managedBeanClass = bean.getClass();
MethodCallback methodCallback =
new ReactiveMethodCallback(configurableBeanFactory, bean);
ReflectionUtils.doWithMethod(managedBeanClass, methodCallback);
}
}
3 - 创建回调方法(这里是执行逻辑)
public ReactiveMethodCallback implements MethodCallback {
private ConfigurableListableBeanFactory configurableBeanFactory;
private Object bean;
public ReactiveMethodCallback(ConfigurableListableBeanFactory bf, Object bean) {
configurableBeanFactory = bf;
this.bean = bean;
}
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (!method.isAnnotationPresent(Reactive.class)){
return;
}
}
}
这里有一个关于注解处理的良好资源,它是关于FieldProcessing的,但是如果您有疑问,只需更改接口以实现您需要的内容即可:https://www.baeldung.com/spring-annotation-bean-pre-processor
[更新] 您还可以创建一个HandlerInterceptor:
HandlerInterceptor
public class ReactiveFilterHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Reactive filter = handlerMethod.getMethod().getAnnotation(Reactive.class);
if (filter != null) {
}
}
return true;
}
}
并注册您的处理程序:
@Configuration
public class WebMvcConfig extends WebMvcConfigurer {
@Autowired
ReactiveFilterHandlerInterceptor reactiveFilterHandlerInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(reactiveFilterHandlerInterceptor);
}
}