Autowiring or setter injection - spring

So far, in our project, we have got our beans having the references set through setter injections; recently, couple of people have started to use #Autowired annotation to set the references on their beans; is it a good to mix annotations and xml configurations for context?

There is no problem using the two together but better to choose one for consistency sake. It would be easier for all the developers to understand and maintain the code.
My preference is annotations as I like things defined at one place.

Mixing annotations and XML definitions works pretty well to reduce amount of code in XML file.
Certainly you can have both coexisting; XML definitions will always override any annotations in Java code without causing a trouble.
Is it good or bad?? I think it's just a way to balance size of an XML file. I find very useful to define my beans in a simple way in XML and then just use #Autowire annotation including #Required to ensure bean has been properly injected before been used.

Related

How to redefine Spring beans representation

I would like to add extra attribute to the internal representation of beans in Spring. Is it possible? What mechanism should be applied if any?
My goal is to define my own beans for my framework. I can do it from scratch or reuse Spring mechanisms.
You could have a look at the documentation Container Extension Points.
To achieve customization you can create a:
BeanPostProcessor bean which operates on a bean instance. For example this allows to create a custom bean registry, to proxify...
BeanFactoryPostProcessor which can operate on bean metadata. This allows for overriding or adding properties even to eager-initializing beans, modifying the class...
BeanDefinitionRegistryPostProcessor which can operate right after the registry initialization. This allows to create, remove or update beans definitions.
For example you can create a new BeanDefinitionRegistryPostProcessor which will register (or modify) beans using a custom implementation of BeanDefinition which will contain custom attribute based on for example your owns annotation.
Could you elaborate a bit what are you trying to achieve with your framework?
Merci beaucoup, Nicolas :)
I will study both your answer and the documentation you provided. I have already found the *Postprocessors you mentioned but I was not sure if this is the right place and what is the nature of their customizations (subclassing or something different) and what are the consequences. My problem is not as simple as I told (not just adding an attribute) - the extended Spring bean should be used also in cooperation to Spring+AspectJ (not SpringAOP), especially with declare-parents construct. I would like to be able to create proxies for the redefined beans as well. I will let you know what are the results of my investigation and may be I will ask some questions.
And the answer to all of you:
My framework is dedicated to defining graph modeling languages (meta-models) at run-time (being far extension of OMG standards) and I am looking for solutions of limits introduced by current object representation in JVM, which promotes behaviour over structure. This is one of several approaches, but the most prospective for me due to the relatively small effort.

#XmlSeeAlso Inheritance

First, I am a newbie in the JAXB and Spring world so if I missed something very obvious I would really appreciate it if someone can point it out instead of not replying. :) I tried searching for a solution here but could not find a good answer.
I have a bunch of subclass DTO's(say A1, A2, A3) which inherit from the same abstract class A. I want the result of my rest query to return a list of the subclass type. I have the following class to represent the result
#XmlRootElement(name="result")
#XmlSeeAlso({A1.class, A2.class, A3.class})
public class AResult<T>
{
...
}
Since AResult is generic I would like the #XmlSeeAlso to also be generic and just write something like
#XmlSeeAlso({(subclasses of A.class})
But I do not think that is possible with JAXB from the research I did on this site and elsewhere.
Since we use the annotation-driven tag in the config, it automatically uses the Jaxb2RootElementHttpMessageConverter class. This message converter creates the JaxbContext using the classes defined in #XmlSeeAlso among others. The createMarshaller and getContext methods are immutable in a superclass.
Because of point 1, I can not write a class where I can check if a class is a subclass of class A and then add it to the JaxbContext. I cannot use a custom Jaxb2RootElementHttpMessageConverter or a custom Marshaller.
How do I get around this? BTW, we are using Spring version 3.1.3
Thanks for your help.
JAXB doesn't scan your classpath for classes that might just happen to be subclasses of AResult (that would be rather slow!) but rather relies on the context knowing about all the classes that it might ever have to create instances of. All the #XmlSeeAlso annotation does is extend the context with the additional classes listed.
However, there are a number of other approaches. For example, you could create a class marked with #XmlRegistry that knows how to make the subclasses that you care about. Or you could experiment with using #XmlJavaTypeAdapter. Alas, I've only ever progressed as far as using the #XmlSeeAlso-based approach in my own code, so I can't comment really from experience.

Spring Transaction Annotations vs Tx Namespace: Which is used more?

I'm studying both of these approaches to include transactions in my Spring application. As for now, I prefer using annotations, as opposed to the tx namespace. The reason is that it sort of clears up the XML/complexity. But this is just my opinion.
I have not had a chance to see what current Spring practitioners use for transactions. Which one is now the preferred approach, and why?
In other words, what are the pros and cons of each approach that ultimately justify the use of one over the other?
<tx:advice> / <tx:attributes> / <tx:method>
Pros
No Spring-dependencies in your code
Very flexible, e.g. make all methods with get prefix transactional but read-only
Easily applying transaction demarcation into wide range of beans
Cons
cumbersome and hard to maintain XML
more XML
...even more XML
#Transactional and <tx:annotation-driven/>
Pros
Dead-simple, just add annotation over class or method
One line of XML (or even none with #EnableTransactionManagement) and it just works
Cons
Spring dependency in your code
Not possible to apply more general rules, like: all classes within a package that end with Dao
I would prefer to use annotations for marking transactions, not because of the ease of configuration or because of concerns about purity of coupling to Spring, but rather because it is typically the case that the code inside the method cannot work correctly without a transaction in place: the annotation is indicating something functional about the implementation as opposed to the way in which the code is managed (which would belong to the Spring configuration file).

Why to use #Autowired on class in Spring

I read about the advantages of using Dependency for interface.
I understand the concept for interface - but why to use #Autowire on class? If we use Autowire on class I know in advance what is the implmeneted class and it's like a regular member of it (without the ability of get to this member)!
What am I missing?
1) Convenience - you do not need to take care for initializing your components, you save time on typing code and configuration files,
2) Forcing good practices - your components to be autowired must be written to be manageable by Spring and spring will take care about error checking for you and pop all errors. So your code will be organized in component collaborating way.
3) Autowiring will also reduce your effort when your classes/beans will grow and evolve.
If you use #Autowire and not call the constructor, you mark the class to be dynamically initialized by the Spring Container. This allows you to set class properties as defined in your spring configuration.
If we use Autowire on class I know in
advance what is the implmeneted class
and it's like a regular member of it
When you wire the dependency through XML instead of Annotations, you also know in advance in which class are you going to inject it.
But You still declare an Interface as dependency, so you can wire any Implementation of this interface at runtime.

object creation in spring

If I am using spring frame work in my application does creating an object like this Test test = new Test() a bad way for creating an instance? Should I always use the bean config to get the objects/bean that I need? If yes, does that means I should have all the object/bean definition in spring applicationContext xml file?
If you want your object to be managed by Spring (this means that dependencies are injected, among other things) you have to use the ApplicationContext.
Calling Test test = new Test() isn't illegal, or even bad practice. It just means that Spring will have no awareness of this object, and it won't bother autowiring it's dependencies, or doing anything else that you'd expect Spring to do.
You don't necessarily need to use the applicationContext.xml file for ALL of your bean declarations. Many people favor annotations, which allow you to declare beans outside of the applicationContext.xml file.
It's worth nothing that Spring-managed beans are by default singletons (think of Servlets). If you want stateful beans that are Spring aware, you could use an ObjectFactoryCreatingFactoryBean to do something like this:
#Autowired
private ObjectFactory myWidgetFactory;
public void doStuff() {
Widget w = myWidgetFactory.getObject();
}
You can read more about this behaviour here:
http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBean.html
For me there's a big difference between objects that represent components of my application -- services, controllers, DAOs, utilities, etc. -- and objects that represent entities within my application -- Person, Order, Invoice, Account, etc. The former type of objects should absolutely be managed by Spring and injected. The latter type are typically created on the fly by the application, and that frequently will involve calling new. This is not a problem.
Test test = new Test() a bad way for
creating an instance?
Yes it is bad practice.
Should I always use the bean config
to get the objects/bean that I need?
Yes, if you are using Spring for dependency injection.
If yes, does that means I should have
all the object/bean definition in
spring applicationContext xml file?
Always! You could use Annotations too.

Resources