Autowiring byName or byType or constructor? - spring

1)In Spring which autowiring in preferred?I am a beginner in learning springs so am not getting which ones to use frequently?Is it that the different types of autowiring have their own advantages and disadvantages?If yes then what?
2)From Springs in action
eg:
<bean id="saxophone"
class="com.springinaction.springidol.Saxophone"
primary="true" />
And all the others their primary is set false.So i can only use this bean for autowiring.So what if i need other beans to autowire which are of the same Instrument type since saxophone is of the Instrument type and that since saxophone is declared primary then how will others be preferred depending upon situations?

No autowiring have advantages or disadvantages. It solely depends upon you, which one to use or your project specification and architecture.
And for your particular example, you have to use byName autowiring.

Related

Single spring bean with two different ids in same xml(application context)

If we create a new another bean with different id in the same xml for the same class, will spring produce another singleton bean(in same ApplicationContext)?
As per my understanding there should be only one instance of the bean in single ApplicationContext.
Below example-
<bean id="bean1" class="com.myCompany.myPackage.MyClass" scope="singleton" />
<bean id="bean2" class="com.myCompany.myPackage.MyClass" scope="singleton" />
To keep it short: No, the singleton only says that you'll have: "one shared instance, which will be returned by all calls to getBean with the given id" (that's what the documentation states).
So, you can do any number of calls to application context and obtain "bean1" and you'll always get the same instance, but if you call by "bean2" id, you'll get another instance.
The "singleton" says that you'll have only one object. Now in a non-Spring application, you'll have it usually per JVM. But in spring application, let the framework manage this. So usually you'll want to define only one class like "MyClass" with a scope singleton.
When dependency management container (Spring in this case) manages singletons, it has a lot of advantages over the 'regular' singleton. Just to name a few:
Much easier to test
You always know when the object is created and when it becomes subject to garbage collector
No static code (the Spring driven singleton is just a regular bean with no statics)
But in general it's not directly related to your question.
I did have this same question just in a different context of Spring's singleton vs. Java's singleton and I found this answer provided by 'Dexter' in this link more subtle and easy to understand.
Also, this blog here provides a perfect example for the same which is backed by the official spring documentation for better-detailed understanding.
Hope these pointers help. Thanks.

Creating non-bean instances with Spring

I'm sure this has been asked a hundred times before but I can't seem to find the question so feel free to refer me to other stackoverflow answers.
What do most Spring users do for objects that are non-singleton beans that require injection? For example, I have classes like Customer where I want to instantiate a new one each time. Lets say it is an entity and I want to inject listeners to iterate through in #PreRemove or somewhere else. The usual solution is to use #Configurable but that almost seems a workaround and I was wonder if there was a more canonical way to handle these.
The only thing I can think of is to create a factory newCustomer instance method in my CustomerRepository class which IS a managed bean. Then instead of injecting listeners into Customer (the most natural place) I inject them into the CustomerRepository and specify them as an explicit constructor argument to Customer ala new Customer( injectedListeners ).
Do people tend to just use Configurable or is there a better way to inject non-singleton instances? Or do most users create a factory method as above? The entity example is just an example, I have other objects that are non-singleton, are typically new'd but require injection.
Would this be handled differently in something like Guice? How would you do it just using JSR-330 features?
You can make beans non-singletons if you like. Depends on whether you are ok with the XML:
<bean id="beanA" class="misc.BeanClass" scope="prototype">
<property ... />
</bean>
Which will give you a new instance every time. Each instance will be initialized with injected values.
You can use this annotation too:
#Scope("prototype")

Inconvenient of #Value Annotation in Spring 3.0

I'm wondering if I add a #Value annotation on a property, the class who contains this property cannot be used by another one with a different value, Example :
MyClassUtil.java had
#Value("${some.value}")
private int _myProperty;
And of course there is one module.properties who contain :
some.value=10
Another class ClassA.java wants to use this class with value 10. Ok, no problem.
But another class ClassB.java wants to use this class but with another value : 20. I cannot do this if I'm not mistaken.
Because before #Value era, I could declare two beans in the moduleContext.xml without any problem.
So, is #Value pushes you to do some strong coupling ?
You are right that the annotation configuration can not be instance specific. It is important to understand the concept of bean definitions in bean factory.
Manual bean definition:
Single <bean> element in your XML config leads to a single bean definition. Multiple <bean> mean multiple definitions (regardless of a bean type).
Single #Bean method within #Configuration class leads to a single bean definition. Multiple #Bean methods mean multiple definitions (regardless of a bean type).
However when using component scan, classes annotated with #Component-like annotations are auto-registered as a single bean definition. There is no way you can register bean multiple times via component scan.
Similarly, annotation configurations (#Value, #Autowired, etc.) are type-wide. Your bean instances are always augmented and processed with the same effect (e.g. injecting the same value). There is no way you can alter annotation processing behaviour from instance to instance.
Is this tight coupling? It is not in its general understanding - bean factory (Spring) is still free to inject whatever it thinks is suitable. However it is more of a service lookup pattern. This simplifies your life when working with domain specific singletons. And most beans in an application context tend to be singletons, many of them domain specific (controllers, services, DAOs). Framework singletons (non-project specific reusable classes) should never use annotation based configuration - in this scope, it is an unwanted tight coupling.
If you need different bean instances, you should not use annotation configuration and define your beans manually.

Spring Bean Inheritance - Scope, autowire, depends-on, etc

From Spring documentation http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-child-bean-definitions:
The remaining settings are always taken from the child definition: depends on, autowire mode, dependency check, singleton, scope, lazy init.
I think there is a good reason for not inheriting these settings, but can't think of one. What are the reasons?
I think it's because it would cause more confusion. Imagine the time spent debugging why your bean is not in the default (singleton) scope. Or the case when the child bean is injected into a bean that the parent depends-on. You will get a circular dependency without being able to notice it.
Bean inheritance is only in terms of properties injected, and not in terms of bean settings.
One of the main reasons is that Spring is used to inject implementations. Usually, extended classes are the implementations and it's natural to pick up the configuration details from their definitions.
Other practical reason is that annotations are not inherited. If an interface has annotated methods this annotation is not automatically visible in the implementing/extending classes without some reflection gymnastics.

Autowired.. more than one?

I am using
<context:component-scan base-package="com.package.dao"/> (Spring 3)
and in my controllers with #Autowired will retrieve automatically the DAO I need. That's perfect and works.
The problem is when I need more than one DAO manager.
How can I do?
I tried with #Qualifier but I am not sure about the name of the dao-manager. className doesn't work
someone can help me?
Thank you!
See in the spring documentation:
#Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even when using the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id
...
If you intend to express annotation-driven injection by name, do not primarily use #Autowired - even if is technically capable of referring to a bean name through #Qualifier values. Instead, prefer the JSR-250 #Resource annotation which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
Use #Resource instead, see here.

Resources