Java 在Spring中向通知发送外部参数
我需要确保特定的方法执行时间小于指定的值。我想做一些如下的事情Java 在Spring中向通知发送外部参数,java,spring,spring-aop,Java,Spring,Spring Aop,我需要确保特定的方法执行时间小于指定的值。我想做一些如下的事情 @Around("execution(* com.foo.bar.executeTask2(..))" + " && someExternalParams(500)") @Around("execution(* com.foo.bar.executeTask(..))" + " && someExternalParams(5)") public void checkSLA(ProceedingJoin
@Around("execution(* com.foo.bar.executeTask2(..))" + " && someExternalParams(500)")
@Around("execution(* com.foo.bar.executeTask(..))" + " && someExternalParams(5)")
public void checkSLA(ProceedingJoinPoint joinPoint, int maxtime) throws Throwable {
//get staarttime
joinPoint.proceed();
// get endtime
if(endtime - starttime > maxtime)
System.out.println("Task took longertime");
}
如何使用SpringAOP实现这一点。一种解决方案是从文件中读取maxtime。有什么想法吗 您的方面是Spring管理的,因此我将从我的方面bean中的属性中读取
@Aspect
public class MyAspect {
@Value("${my.system.property.for.max.time}")
private int maxTime;
@Around("execution(* com.foo.bar.executeTask(..))")
public void checkSLA(ProceedingJoinPoint joinPoint) throws Throwable {
//get staarttime
joinPoint.proceed();
// get endtime
if(endtime - starttime > maxTime)
System.out.println("Task took longertime");
}
}
}
您好,您可以制作一个
@SLA
注释,并从您的方面中读取该值。显然,您必须更改advice以匹配该注释,并使用@SLA
注释标记所有方法
这与您的方法有一点不同,但我认为为这种方面做注释更好。这样,您就不必在每次需要处理新方法时都更新切入点。只需将注释添加到此方法。见下面的例子
注释:
@Target(METHOD)
@Retention(RUNTIME)
public @interface SLA {
int maxtime();
}
方面:
@Aspect
public SLAAscpet {
@Around("execution(@com.foo.bar.SLA * *(..))")
public void aroundSLAMethod(final JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
SLA annotation = signature.getMethod().getAnnotation(SLA.class)
int maxtime = annotation.maxtime()
...
}
}
用法:
...
@SLA(maxtime=500)
public void someMethodForSLA() {
...
}
...
因为我是AOP新手,所以我正在寻找一个例子。如果你能给我指一些资源那就太好了。我看了@args,但它们的用途完全不同。参数来自哪里?正在代理的方法的调用方?我认为您可以
@Autowired
将此配置引入您的方面,因为它是Spring管理的,并且所有...@nicholas.hauschild我希望为特定任务提供此maxtime限制。是的。我正在使用
。我打算将这段代码作为Logger/Profiler的一部分,我不想将其与业务逻辑混淆。谢谢。但是如果我有另一个需要不同SLA的方法executeTask2()
,我该怎么做呢?我相应地更新了问题。您是否有第二个(或第三个,或第四个…)建议来区分可接受的时间值?我想让slaapect
成为一个通用的建议。我喜欢将其应用于系统中的任何服务方法,以查看响应时间是否在限制范围内。因此,我正在寻找一种可扩展的解决方案。我可以有分离装置,但它们是一样的。所以我想知道我能不能给你一个建议来完成这项工作。谢谢。我可以从属性文件中获取最大时间吗。类似这样的东西@SLA(maxtime=${“maxtimeproperty”})
。我可以在这里使用@Value
吗?我希望maxtime可以在运行时配置,而无需重新部署应用程序。