ฉันอยากจะใช้สีกำหนดเองของจาวาหมายเหตุประกอบ annotation tool ต้องใส่ค่าส่วนตัวในการเรียนทรัพย์สินโดยใช้ฤดูใบไม้ผลิ AOP(และ/หรือ AspectJ). เร็วตัวอย่าง:
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()
และหลังจากมันกลับมา ฉันอยากจะเห็น"helloworld" ในคอนโซลหรือของบันทึกการปฏิบัติ ฉันต้องสักตั้ง var1
ต้องการกำหนดค่าใช้ AOP. มีทรัพย์สินตัวแปรนั้นจะถูก annotated กับ @MyAnnotation
จะถูกตั้งค่าเป็น"helloworld". ฉันหวังว่าตัวอย่างอยู่เหนือมันชัดอยู่แล้ว
อะไรฉันพยายามหรอ?
ดิฉันไปตรวจสอบให้แน่ใจว่าไม่มี typo อยู่ในห่อของชื่อเหมือนกั fiddled กับต่างออก AOP คำแนะนำหมายเหตุประกอบเหมือน @Around
แล้ว @Before
. ฉันยังพยายามแตกต่างเป้าหมายใน MyAnnotation
และลงเอยกับ ElementType.FIELD
ซึ่งน่าจะถูกต้อง
คุณสามารถช่วยฉันจะเอามันไปทำงานเหรอ?
ฉันรู้ว่ามันสามารถทำได้แต่ไม่สามารถหางานตัวอย่างเช่นทางออนไลน์ อีกครั้ง,ฉันอยากจะเห็น 2 คำตอบ:
1. วิธีที่จะเอา pointcut ต้องกระตุ้นใน MyController ทางเข้า? ฉันอยากจะจับเป็นจุดหยุดข้างใน enrichVar1(..)
วิธีการของ MyAspect
ห้องเรียน
2. จะให้ฉันแก้ไขค annotated var1
ค่าอยู่enrichVar1(..)
วิธีการของ MyAspect
ห้องเรียนด้วยได้ไม๊?
ฉันไม่รู้ว่าฉันทำอะไรผิดพลาด ที่เขาแนะนำให้ผูกผ้ากันเปื้อนจะเป็น greatly นเกียรติอย่างยิ่ง ขอบคุณ!
ที่ AOP จะถูกตั้งขึ้นอย่างถูกต้องในโครงการ ฉันรู้เพราะฉันแล้วใช้ AOP สำหรับในสิ่งที่แตกต่างกันออก(การทำปูมบันทึกสำหรับตัวอย่าง).
ปรับปรุง#1:
ได้โปรดโน้ตไว้มันไม่ใช่รักหรื setters สำหรับ var1
ส่วนตัวตัวแปร ตัวแปรจะถูกใช้ภายใน MyControllerImpl
. ต้อง illustrate มันจะดีกว่าถ้าฉันเปลี่ยนกลับค่า getVarExample
.