Java 使用注释在服务调用之前/之后插入我的代码
该服务是一个Springbean,它@autowired到我的类中:Java 使用注释在服务调用之前/之后插入我的代码,java,annotations,interceptor,Java,Annotations,Interceptor,该服务是一个Springbean,它@autowired到我的类中: public class MyClass { @Autowired private Service service; private void myMethod() { service.call(); } } call()方法可能会抛出异常,因此我用try-catch行将其包装起来: public class MyClass { @Autowired priv
public class MyClass {
@Autowired
private Service service;
private void myMethod() {
service.call();
}
}
call()方法可能会抛出异常,因此我用try-catch行将其包装起来:
public class MyClass {
@Autowired
private Service service;
private void myMethod() {
try {
service.call();
} catch (Exception e) {
// do some logging
}
}
}
如何编写自定义注释并自动执行此操作?像这样:
public class MyClass {
@Monitored
@Autowired
private Service service;
private void myMethod() {
// it will be logged if call() throws exception
service.call();
}
}
谢谢你的帮助。有很多例子,比如or。你应该有一个
建议来说明你想要的方法。并为要截取的方法定义一个切入点。查看有关不同类型建议的更多信息(我相信您的案例中之前和之后或周围都是合适的)和一些示例。如果您想在每次调用该方法时触发代码,您是否仔细研究了Spring AOP?这似乎是一个完美的用例。