我想使用的定义Java注中插入一个值在私人类财产的使用弹簧AOP(和/或模型或许). 简单的例子:
MyAnnotation.java:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface MyAnnotation {
}
MyController.java:
public class MyControllerImpl implements MyController {
...
@MyAnnotation
private String var1;
@Override
public String getVarExample() {
// imagine this is a REST API that gets called on @GET
// request and returns a string
System.out.println(this.var1); // <-- I'd like this to be "helloworld"
// this is just for illustration
// of course, I will want to do
// something more meaningful with
// the 'var1' variable
return "ok"; <- unimportant for this example
}
...
MyAspect.java:
@Aspect
@Component
public class MyAspect {
@Pointcut("@annotation(com.mypackage.annotation.MyAnnotation)")
public void fieldAnnotatedWithMyAnnotation() {
}
@Around("fieldAnnotatedWithMyAnnotation()")
public Object enrichVar1(ProceedingJoinPoint pjp) throws Throwable {
// problem #1 - the program never enters here
// problem #2 - I need to figure out how to set up the var1 here
// to "helloworld" , how?
return pjp.proceed();
}
...
}
什么我喜欢来发生的?
我会打电话和获得进入 getVarExample()
后它返回 我想看看"案" 控制或记录。 我想以某种方式设置 var1
一定值采用AOP。 任何财产的变量将被标注了 @MyAnnotation
将设置为"建". 我希望上述例子是清楚的。
什么我有没有试过吗?
我确定没有错字中包名,也摆弄不同AOP咨询意见的注释喜欢 @Around
和 @Before
. 我也尝试了不同的目标 MyAnnotation
并且结束了 ElementType.FIELD
这应该是正确的。
你能帮助我得到它的工作?
我知道这是可以做到的,但无法找到任何工作,例如在线。 再次,我要看看2的答案:
1. 怎么得到的切入点的触发MyController入口? 我想要抓住一个断点的内部 enrichVar1(..)
方法 MyAspect
类。
2. 我怎么可以修改附加说明的 var1
值enrichVar1(..)
方法 MyAspect
课吗?
我不知道我在做什么错误的。 任何帮助,将不胜感激。 谢谢你!
AOP设置正确,在我的项目。 我知道因为我已经使用AOP不同的东西,(日志为例)。
更新#1:
请注意有没有吸气,或者以为 var1
私人可变的。 变量将仅仅用于内 MyControllerImpl
. 为了说明这个更好的我改变了回返值 getVarExample
.