Entity Aspect (in Spring)

隐身守侯 提交于 2019-12-14 04:25:18

问题


I'm having a bit of a problem defining my aspects. I've got a bunch of entities that I'd like to profile the get-methods in, so I've written the following pointcut and method

@Pointcut("execution(* tld.myproject.data.entities.*.get*()")
public void getEntityProperty() {}

@Around("getEntityProperty()")
public Object profileGetEntityProperty(ProceedingJoinPoint pjp) throws Throwable {
    long start = System.currentTimeMillis();
    String name = pjp.getSignature().getName();
    Object output = pjp.proceed();
    long elapsedTime = System.currentTimeMillis() - start;
    if(elapsedTime > 100)
        System.err.println("profileGetEntityProperty: Entity method " + name + " execution time: " + elapsedTime + " ms.");
    return output;
}

I've got weaving turned on in my configuration, and aspects weaving into the business layer work just fine. Is my pointcut correctly written? Or is there something about entities that make them non-weavable? (my entity is prefixed with @Entity before the class definition)

Cheers

Nik


回答1:


You're only a parenthesis away actually!

@Pointcut("execution(* tld.myproject.data.entities..get())")


If you're using Eclipse, I will recommend developing with AspectJ compile-time weaving. It's the simplest way.

With the AJDT plugin, you get lots of help! I just pasted in your pointcut and got an compilation error. Added a parenthesis and it worked!

Screenshot of visual support with the AJDT plugin:

The orange arrow to the left of the getHello() method indicates that is's advised by an around advice. See here for a larger example.




回答2:


Yes, there is. The entities are created by you, using the new operator, and hence they are not part of the spring context.

If you want to use this, you'd need to enable weaving (I prefer load-time via <context:load-time-weaver/>), and to annotate your entity classes with @Configurable.

I, personally, wouldn't prefer this practice. Alas, there aren't any alternatives that are so generic. If your persistence provider is Hibernate, you can create a custom proxy of your entities - see here, but this is even more awkward.




回答3:


Just a note that @Configurable works with compile-time weaving. The drawback to autowiring entities via @Configurable is that they don't 'seem' to work when retrieving said entities from a database via Hibernate. Via a 'new' invocation, yes. But just recently, given a very weird request to do persistence from an entity, a unit test using 'new' worked perfectly, yet hibernate (or ehcache) loaded-entities resulted in NPEs for the autowired property. It was late at night; so you may wish to do some testing yourself.:) Just passing along my recent experience. Hope it helps.



来源:https://stackoverflow.com/questions/2910846/entity-aspect-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!