Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoiding problems with spring cglib proxy

Using cglib proxies in spring causes:

a) double invocation of constructor

b) not allow to intercept a method invoked from another method

but why spring creates a bean and then a proxy? is it possible to dynamically generate class that extends a specified bean class and then invoke constructor only once? that would solve a) and b) for public and protected methods. am i missing something?

like image 385
piotrek Avatar asked Oct 20 '12 10:10

piotrek


1 Answers

Good question. I think it's due to how Spring bootstraps application context: it first creates all raw beans and then applies post processors, e.g. adding AOP (including transactions). This layered architecture requires creating normal bean first and then wrapping it. One might argue that this approach follows composition over inheritance principle.

Also note that a) should not be a problem. Class should not perform initialization in constructor but in @PostConstruct method - which is invoked only once. On the other hand this leads to another issue:

c) one cannot use constructor injection with CGLIB proxies, see SPR-3150

But I understand your frustration. Guess the only valid workaround is to us full AspectJ weaving.

like image 72
Tomasz Nurkiewicz Avatar answered Oct 30 '22 12:10

Tomasz Nurkiewicz