我有一些控制器的spring引导应用程序。
所有控制器都具有带有路径/值属性的@RequestMapping注释。我希望在运行时通过链接到bean生命周期来更改此属性的值。
我正在使用BeanPostProcessor.postProcessBeforeInitialization()来完成这个任务,下面是我使用的反射代码:
public class RequestMappingProcessor implements BeanPostProcessor
{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
{
RequestMapping requestMapping = bean.getClass().getAnnotation(RequestMapping.class);
System.out.println("OldAnnotation Value " + requestMapping.value()[0]);
Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(requestMapping);
String[] values = (String[]) attributes.get("path");
var newValue = getNewPath(path);
Object handler = Proxy.getInvocationHandler(annotation);
Field f;
try
{
f = handler.getClass().getDeclaredField("memberValues");
}
catch (NoSuchFieldException | SecurityException e)
{
throw new IllegalStateException(e);
}
f.setAccessible(true);
Map<String, Object> memberValues;
try
{
memberValues = (Map<String, Object>) f.get(handler);
}
catch (IllegalArgumentException | IllegalAccessException e)
{
throw new IllegalStateException(e);
}
Object oldValue = memberValues.get(key);
if (oldValue == null)
{
throw new IllegalArgumentException();
}
memberValues.put(key, newValue);
memberValues.put("path", newValue);
System.out.println("New Annotation Value " + requestMapping.value()[0]);
}事情是这样的,我确实看到它在控制台上打印更新的值,但是当我在postman或浏览器中检查实际端点时,旧路径仍然有效,而不是新的路径。JDK 17
我知道许多人会建议为所有控制器和所有控制器在API级别设置前缀路径,但在我的示例中,每个控制器可能基于某种注释具有不同的前缀。如果你有其他建议,请提出建议。
发布于 2022-08-31 19:44:51
对于那些想要完成同样任务的人,您可以通过在自定义配置器中重写WebMvcConfigurer.configurePathMatch(PathMatchConfigurer configurer)方法,并根据使用configurer.addPathPrefix()的自定义逻辑为所有控制器设置前缀。
https://stackoverflow.com/questions/73522559
复制相似问题