【发布时间】:2019-08-30 22:48:32
【问题描述】:
我有类似的控制器
@MessageMapping("/room.register")
@SendTo("#{sendTo}")
public Message addUser(@Payload Message message,
SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("username",
message.getSender());
return message;
}
我想在运行时更改 SendTo 注释的值。
我尝试如下:
@Aspect
public class SendToAspect {
@Autowired
private WebSocketConfigurationProperties webSocketConfigurationProperties;
@Around("execution (public * *(..)) && @annotation(ann)")
public Object execute(final ProceedingJoinPoint point, final SendTo ann)
throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
method.setAccessible(true);
Annotation[] annotations = method.getDeclaredAnnotations();
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].annotationType().equals(SendTo.class)) {
annotations[i] = new SendTo() {
@Override
public Class<? extends Annotation> annotationType() {
return SendTo.class;
}
@Override
public String[] value() {
return new String[]
{webSocketConfigurationProperties.getTopic()};
}
};
}
}
return point.proceed();
}
}
但是这只在注解数组(Annotation[]注解)中改变,在方法注解(method.getDeclaredAnnotations())中没有改变。
请告诉我该怎么做,有可能吗?
【问题讨论】:
-
注解是在编译时确定的,这就是为什么它们只能包含常量。至于你的问题,你踏入了一个叫做XY problem的陷阱。不要试图解释如何您想解决您的问题,而是告诉我们您想要实现的什么。为什么心智正常的人会想要更改注释?
-
@kriegaex 嗨!我只想从属性值-apllication.yaml 中读取注释值(SendTo (value = ".."))。我之前问过这个问题,但没有找到解决方案stackoverflow.com/questions/57677433/…
-
您可能想查看destination variable placeholders 以及我对how to evaluate SpEL (Spring Expression Language) 的回答。也许这两种方法中的一种对您来说是可行的。不过,我不是 Spring 用户,只是 AOP 专家。可能有更好的车载方式来实现您想要的。
标签: java reflection annotations aop