I have the similar problem as described in this thread: http://forum.spring.io/forum/attic/spring-modules/22590-can-t-cache-result-of-inner-method-call
But I don't like to decompose my bean in a chain just for caching. In my case I need to create a chain of three fake beans just for caching!
I understand that the caching proxy just delegates all calls to the original bean, so inner calls cannot be intercepted. I understand this in case of java config -- I've just created my bean with the 'new' keyword. But why I got the same behavior on xml config? I expect that Spring can extend my class with its constructors and create an instance of a new class. So all inner calls will be also go through the caching layer due to polymorphism.
Is there any way to force inheritance but not delegation to the original bean?
Thanks,
Alexey
I've just found the chapter in the reference. It says that "Spring AOP is proxy-based." There is a way to access reference to a real proxy: AopContext.currentProxy()) to call it instead of "this" bean.
Related
I'm studying spring beans and came across #Lookup, it says:
If we happen to decide to have a prototype Spring bean, then we are
almost immediately faced with the problem of how will our singleton
Spring beans access these prototype Spring beans?
hmm, I don't get it, because when I studied scope=prototype it says:
4.4.2 The prototype scope
The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a
request for that specific bean is made
so it seems i misinterpreted the words:
a request for that specific bean is made
actually programming in spring framework every line of the code is inside of some bean (i.e. #controller, #Service, etc), isn't it?
And almost all of them are singletons, isn't it?
So if I need prototype I just make scope=prototype and almost everytime it's injected to another bean (i.e. #controller, #Service, etc) isn't it?
So please give a real world scenarios, 1) when one should use #Lookup and 2) when it's not needed
Ok for the 1) the scenario:
#Component
#Scope("prototype")
public class SchoolNotification {
// ... prototype-scoped state
}
#Component
public class StudentServices {
// ... member variables, etc.
#Lookup
public SchoolNotification getNotification() {
return null;
}
// ... getters and setters
}
Please, show me scenario for the 2) case, and explain please the difference
Thank u
The implicit Bean scope in Spring is Singleton.
That means for a JVM instance, only a single instance of a Bean exists in memory (theoretically).
When you #Autowire a Prototype-scoped Bean inside a Singleton-scoped Bean, that Prototype one becomes a sort-of-singleton. Just think about it; a Singleton gets created, its injectable fields get Autowired, and that is it, the instance lives forever along with all its fields (keep in mind those Prototype-scoped fields are "pure" instances, they're not proxied).
#Lookup
is a proxy-driven annotation. What that means is Spring will extend your class using JDK proxies or CGLIB proxies, and it will override/implement the #Lookup-annotated method, providing its own version which uses a BeanFactory#getBean each time it is invoked.
The documentation is clear on this point
An annotation that indicates 'lookup' methods, to be overridden by the
container to redirect them back to the BeanFactory for a getBean call.
Thus, that means a fresh Bean instance is returned every time.
Just for your knowledge, another approach for working with Prototype-scoped Beans inside "other"-scoped Beans is using ProxyFactoryBean. The only difference is that the proxy is created at configuration-time, and then made available for direct #Autowireing, thus not requiring the definition of a #Lookup method, which sometimes is not wanted (usually by folks that are obsessed with clean code, like me).
I am studying Spring and I have the followig
Consider the following bean definition:
<bean id="clientService" class="com.myapp.service.ClientServiceImpl" />
Now consider the case on which it is declared a pointcut* targetting all methods inside the **clientService bean.
Consider also that the ClientServiceImpl class implements 3 interfaces
Now I know that using AOP the clientService bean is proxied and that this proxy implements all the 3 interfaces.
But what is the exact reason for which all these 3 interface are implemented?
So it seems to me that exist 2 kinds of proxies (correct me if I am saying wrong assertions):
JDK Proxy: used by default from Spring (is it true?) in wicht I have an interface that define the method of the object that I want to proxify. So the concrete implementation of this interface is wrapped by the proxy. So when I call a method on my object I am calling it on its proxy. The call is recognized by a method interceptor that eventually perform the aspect and then is performed the invoked method.
CGLIB Proxy: in wich, it seems to me that, the proxy extend the implementation of the wrapped object adding to it the extra logic features
Something like this:
So it seems to me that Spring use the first kind of proxy that is based on the implementation of interfaces (is it right?):
I think that in AOP the extra logic is represented by the implementation of the method interceptor (is it true?) and the standard logic is represented by the implementation of the method defined into the interfaces.
But, if the previous reasoning are correct, my doubts is: why I need to define these interface and do that the object wrapped by the object implement these interfaces? (I can't understand if the proxy itself implement these interfaces).
Why? How exactly works?
Tnx
But what is the exact reason for which all these 3 interface are
implemented?
If the proxy didn't implement all of those interfaces, the bean couldn't be wired into other beans that use that interface (you'd get a ClassCastException). For example, autowiring all of the beans of that interface into a bean. Additionally, things like getBeanNamesForType wouldn't work if the proxy didn't implement the interface.
So it seems to me that exist 2 kinds of proxies (correct me if I am
saying wrong assertions)
Yes that's correct. See ScopedProxyMode. By default, Spring won't create a proxy. It only creates a proxy if it needs to wrap the bean to add additional behavior (AOP). Note that there's also a special case of the CGLIB based proxy that uses Objenesis to deal with subclassing targets that don't have a default constructor.
CGLIB Proxy: in wich, it seems to me that, the proxy extend the
implementation of the wrapped object adding to it the extra logic
features
When you use CGLIB based proxies, the constructor for your bean gets called twice: once when the dynamically generated subclass is instantiated (to create the proxy) and a second time when the actual bean is created (the target).
I think that in AOP the extra logic is represented by the
implementation of the method interceptor (is it true?)
The proxy is essentially just invoking the chain of advice needs to be applied. That advice isn't implemented in the proxy itself. For example, the advice for #Transactional lives in TransactionAspectSupport. Take a look at the source to JdkDynamicAopProxy.
and the standard logic is represented by the implementation of the
method defined into the interfaces.
Assuming that you're programming against interfaces and using JDK proxies that's correct.
But, if the previous reasoning are correct, my doubts is: why I need
to define these interface and do that the object wrapped by the object
implement these interfaces? (I can't understand if the proxy itself
implement these interfaces).
If you want to use interface based proxies you need to use interfaces. Just make sure all of your beans implement interfaces, all of your advised methods are defined by those interfaces, and that when one bean depends on another bean, that dependency is specified using an interface. Spring will take care of constructing the proxy and making sure it implements all of the interfaces.
In your diagram, you have "Spring AOP Proxy (this)". You have to be really careful with using this when you're using any type of proxying.
Calls within the same class won't have advice applied because those calls won't pass through the proxy.
If in one of your beans you pass this to some outside code, you're passing the target of the AOP advice. If some other code uses that reference, the calls won't have AOP advice applied (again, you're bypassing the proxy).
Please pardon this Spring beginner question. I am reading chapter 4 of first edition and being introduced to both call-back method and Bean post processor.
Now I am just getting confused about the two, it seems like they both do sth. when the bean instance is created, so how can I differentiate the two? Maybe an example would be good?
My personal understanding is, if we have to find a difference, then call-back method is initiated when the bean gets actually created, the Bean post processor gets called slightly after the creation of the bean?Also, I think the diference might also be that initalization call-back method focus on one bean only while Beanpost procsso will pocess all the bean instances one by one?
Also, could anybody help me further explain the difference by comaring and contrasting JSR250 annotation #PreDestroy and #PostConstruct with the two concepts above?
Thank you very much for helping!
It's been a while since I've used either of these, but I think the callback method and #PostConstruct methods you are referring to are the same thing. But to answer your question, the difference....
1) The #PostConstruct (or afterPropertiesSet) method is a method internal to a specific class that will be called after a bean is instantiated. This is really where you put type-specific actions.
2) The BeanPostProcessor will touch all Spring beans. So here's where you can put cross-cutting functionality, not necessarily class-specific.
A small example... say I have a small address book application for keeping track of my friends and their addresses. If I have some crazy bug I can't track down, I might use a BeanPostProcessor to wrap all my Spring beans with some logging, such as "now invoking Address.getStreet()..., now invoking Address.getCity()...".
Now I might use a #PostConstruct method in Address to verify and look up zip codes against some web service for addresses where I only have city/state.
Now, I might not actually have one of my domain objects hitting a web service in reality, but the idea is to illustrate that a #PostConstruct can handle class specific stuff and a BeanPostProcessor can take care of things that span multiple classes.
Also it's worth noting, that BeanPostProcessor has two methods to override: postProcessBeforeInitialization and postProcessAfterInitialization, which will let you decide what to run before and after the bean's #PostConstruct method.
Bean post processors interface has two callback methods: 1. PostProcessBeforeInitialization and PostProcessAfterInitialization.
PostProcessBeforeInitialization method is invoked just before calling your init-method or afterPropertySet method of the bean.
PostProcessAfterInitialization method is just called after just after the initialization of bean completed.
Bean Post Processors gives chance to do something before and after initialization of bean.
Consider a line of code like this
AutomobileDriver ad=(AutomobileDriver)appContext.getBean("increaseSpeed");
Assume there is an IncreaseSpeed class which inherits from AutomobileDriver class
What does getBean do? What is the main function of this?
In "simple layman's terms":
This assumes that Spring was told to create an object instance (possibly in an XML config file) that is identified (by Spring) as with the id "increaseSpeed" and has a class or parent class of AutomobileDriver.
You are asking the Spring context for a reference to (a) by default, the previously created object (this is called a singleton) or (b) a new instance of that object (prototype).
In Spring, you can define a bean and give it an id. Usually, Spring would prefer that you use dependency injection to access the bean. However, Spring provides getBean as another way to access a bean by its id.
Basically, your code will return an instance of the bean with id "increaseSpeed".
This code is requesting the bean named increaseSpeed from the Spring Application Context. Think of the application context as the pool of available objects, which has been configured from your Spring configuration XML. When the application context is started, it creates the beans in the configuration. This call simply asks for the one which is already there. The application context returns this "bean" as a java.lang.Object so you have to cast it to the appropriate type.
You might see this call as an entry point in a Spring application. This call is needed to get the first object out from the application context - from there, this object may have links to other objects which have been injected by Spring.
A bean is a component that provides some functionality, the name of the bean indicates that it would be increase speed.
Those components are registered in a context called 'application context' and can be looked up by name. So if you want to increase the speed look at your apps-context for something that could do this.
More tecnical:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
When using Spring AOP to create a proxy for a class using NameMatchMethodPointcutAdvisor and BeanNameAutoProxyCreator does this essentially proxy every call to the object, but only apply the advice to the matched methods, or somehow create a Proxied object that only has those methods and uses the normal object for the calls that are supposed to be intercepted?
The way, I think I understand it is that it does proxy every call to the object but then only calls the Advisor on the methods that match - but I can't find a good example/post to confirm this.
Depends on the technique used. (It is configurable by an attribute proxy-target-class in your aop config)
JDK dynamic proxies are proxies by interface - each methods of the interface goes through the proxy, as you said, and if it matches happens to be an "advised" method, the advisor is applied. Otherwise it is delegated to the original object
CGLIB proxies are effectively subclasses defined at runtime of your concrete classes. I can't be sure in this, but I assume only the "advised" methods are overridden, the rest retain the definition of the superclass.
However, no matter which mechanism is used:
it isn't your concern how exactly are the proxies implemented
this doesn't impact performance in a significant way - Debunking myths: proxies impact performance by the Spring team about proxy performance myths
or somehow create a Proxied object that only has those methods and uses the normal object for the calls that are supposed to be intercepted?
How would this actually work? When a class has a reference to the class that is being proxied, it only has one reference to it. It either has to invoke a proxy class or a non-proxied class. Spring can't know which methods you are calling and therefore can't give you one type if you need to call the advised method and another type if you're not.