So I have a set packages that are my base code for extended applications. My application implements a series of interfaces that then are inject by spring during run time (As configured). I would like to know is there is a way that I could know which class that implements the interface was injected. I need this because I have JSON serializer/deserializer actions that I would like to perform but for that I need to know the class that was injected.
I have an java config file that will describe the wiring and it will be provided with the game implementation. But so far I haven't been able to get the concrete class implementing the interface. I also haven't been successful to request that info from the context.
Ant hints?
You can use reflection to let the injected instance tell you what implementation class it is: injectedInstance.getClass().getName(). However, unless you're doing something special, consider this a hack. You probably should revisit your design so that you do not need to do that.
You can simply autowire an interface and get the implemented class name:
#Autowired
private Service service;
System.out.println(service.getClass().getName());
However with Spring beans the spring container has usually proxied them so it's not always helpful, in the case above the class is a Spring class called:
hello.HelloServiceImpl$$EnhancerBySpringCGLIB$$ad2e225d
I suspect you should look at Jackson serializers which should handle all this, see Java - Jackson Annotations to handle no suitable constructor
So the way I came around this issue was by injecting an object into the JSON deserializer and use a getClass() method as the template to Jackson to use. And it worked like a charm, even thought the implementation to be injected was injected into a wiring happening in the dependency!. Hope it helps!
Related
From a software design perspective, when should we use #Component instead of a traditional Java class (that needs to be explicitly instantiated by 'new')? For example, if we need to create a class that is one of the following patterns:
Adapter
Bridge
Façade
Strategy
Translator
Should the class have the #Component annotation (or any Spring derivative annotation such as #Repository/#Controller/#Service)?
Spring applies the Inversion of Control principle, which drills down to that the framework handles stuff for you, so you don't have to worry about it.
By using #Component on the class you let Spring create a bean for you.
This way Spring can, for example, inject this bean on runtime when you need it. (For example by Autowiring your constructor).
It is up to you to decide if you want to make use of this functionality for your class. A facade for example could very well be a Spring component, this way you could possibly inject an API implementation that is exposed via a facade on runtime, without the need to think about the dependency injection implementation.
I would not recommend using this annotation on a DTO or model class for example. These classes mostly consist of data and don't fit the need to be managed by Spring.
Other interesting related questions that can help you decide when to create a component:
What's the difference between #Component, #Repository & #Service annotations in Spring?
Spring: #Component versus #Bean
I'm working on a utility for supporting context-dependent injection, i.e. what gets injected can now also depend on where it is injected. Logger injection is a common application of this technique.
So far, I've successfully implemented this for HK2 and Guice, and with some limitations for Dagger.
To solve this for Spring, I'm using a BeanFactoryPostProcessor that registers an AutowireCandidateResolver. However, to achieve the intended semantics, I need to know the type of the actual target object, which may be different from the type that declares the injection point. For example:
class BaseClass {
#Inject Logger logger;
}
class SubClass extends BaseClass {
}
Instances of SubClass need to be injected with a logger for SubClass, not with a logger for BaseClass.
The DependencyDescriptor contains this information in the containingClass field, but unfortunately this information is not exposed via the API.
Question 1: Is there an architectural reason that this information is not exposed, or could a getter for this be added to the DependencyDescriptor API?
Question 2: In the meantime, what is the best way to work around this limitation? Accessing the internal field via the Reflection API is ugly and violates encapsulation. The other alternative is to inject the wrong (i.e. Logger for BaseClass) instance first and then later correct it with a BeanPostProcessor, but I would be manually redoing a lot of work (i.e., reprocessing pretty much the entire injection handling).
Now quite sure what is the reason of the strictness of DependencyDescriptor API. But the starting point for you should not be the BeanFactoryPostProcessor but you should have a look at BeanPostProcessor and particularly at AutowiredAnnotationBeanPostProcessor which autowires annotated fields, setter methods and arbitrary config methods based on the #Autowired, #Value and #Inject annotations. As I understand this is what you want to do. This class is the responsible for creating DependencyDescriptor.
So may be what you need to do is:
Create a custom DependencyDescriptor (just extend it with public access to "containing class")
Create a custom AutowiredAnnotationBeanPostProcessor which will do same things as AutowiredAnnotationBeanPostProcessor but instead of creating the instance of DependencyDescriptor will create the one from step 1.
Create a custom AutowireCandidateResolver which will just cast the DependencyDescriptor to the one which you have created (so can publicly access "containing class" property.)
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).
This concept is unclear with me.
I have worked on several frameworks for an instance Spring.
To implement a feature we always implement some interfaces provided by the framework.
For an instance if I have to create a custom scope in Spring, my class implements a org.springframework.beans.factory.config.Scope interface. Which has some predefined low level functionality which helps in defining a custom scope for a bean.
Whereas in Java I read an interface is just a declaration which classes can implement & define their own functionality. The methods of an interface have no predefined functionality.
interface Car
{
topSpeed();
acclerate();
deaccelrate();
}
The methods here don't have any functionality. They are just declared.
Can anyone explain this discrepancy in the concept? How does the framework put some predefined functionality with interface methods?
It doesn't put predefined functionality in the methods. But when you implement
some interface (say I) in your class C, the framework knows that your object (of type C)
implements the I interface, and can call certain methods (defined in I) on your object
thus sending some signals/events to your object. These events can be e.g. 'app initialized',
'app started', 'app stopped', 'app destroyed'. So usually this is what frameworks do.
I am talking about frameworks in general here, not Spring in particular.
There is no conceptual difference, actually. Each java interface method has a very clear responsibility (usually described in its javadoc). Take Collection.size() as an example. It is defined to return the number of elements in your collection. Having it return a random number is possible, but will cause no end of grief for any caller. Interface methods have defined semantics ;)
As I mentioned in the comments, to some extent, implementing interfaces provided by the framework is replaced by the use of stereotype annotations. For example, you might annotate a class as #Entity to let Spring know to manage it and weave a Transaction manager into it.
I have a suspicion that what you are seeing relates to how Spring and other frameworks make use of dynamic proxies to inject functionality.
For an example of Spring injecting functionality, if you annotate a method as #Transactional, then the framework will attempt to create a dynamic proxy, which wraps access to your method. i.e. When something calls your "save()" method, the call is actually to the proxy, which might do things like starting a transaction before passing the call to your implementation, and then closing the transaction after your method has completed.
Spring is able to do this at runtime if you have defined an interface, because it is able to create a dynamic proxy which implements the same interface as your class. So where you have:
#Autowired
MyServiceInterface myService;
That is injected with SpringDynamicProxyToMyServiceImpl instead of MyServiceImpl.
However, with Spring you may have noticed that you don't always need to use interfaces. This is because it also permits AspectJ compile-time weaving. Using AspectJ actually injects the functionality into your class at compile-time, so that you are no longer forced to use an interface and implementation. You can read more about Spring AOP here:
http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-introduction-defn
I should point out that although Spring does generally enable you to avoid defining both interface and implementation for your beans, it's not such a good idea to take advantage of it. Using separate interface and implementation is very valuable for unit testing, as it enables you to do things like inject a stub which implements an interface, instead of a full-blown implementation of something which needs database access and other rich functionality.
How would you extract something prior 2.5 version from .xml config? It bothers me because if #Autowired is removed from my arsenal I would not really know what to do.
Say I want to use some DAO implementation.
In service class I usually write:
#Autowired
someDaoInterface generalDao;
Then I typically call
generalDao.someInterfaceMethod(someParam param);
How would I extract implementation from config in Spring 2.0 to use this method?
Is it as dumb as just: new ApplicationContext(pathToXml) and then use .getBean or there is other way?
Why do I ask for taking bean out from configuration file?
Because in Spring MVC how can you perform your logic without getting beans out from the application context.
If you have #Controller handler then you need to make calls to the service classes' methods? So they should be somehow retrieved from the context and the only way so far is using #Autowired? Then I would also want to populate Service classes as I stated in previous example with DAO classes and they also need to be retrieved from the application context, so I would be able to write logic for service classes themself. How would people do it in the past?
I see the #Autowired as the only mean of taking something out, not because it is convenient to wire automatically - I am perfectly ok with XML.
You still have option to wire it explicitely via property or constructor parameter. (Anyway, autowired is not going to work if there is ambiguity in your container )
Of course, you can use application context and getBean() in your java code, but it violates DI pattern and makes all the spring stuff useless. Purpose of DI is to decouple your business loginc from implementation details - it's not business logic it's how and where it dependencies come from. Dependencies are just there.
By using ApplicationContext.getBean() you are breaking this pattern, and introduce dependency to:
spring itself
your configuration names
After you done this, you can as well drop use of DI and spring because you just voided all the advandages DI is providing to you. (BTW, #Autowired also introduces dependency to spring, and violates DI pattern, it also implies that there is only one instance available)
Also, answer is: in ideal case there shall be no reference to spring in your code at all.
No imports, no annotations - just interfaces of collaborating entities.