What does it mean when Weld says "unsatisfied dependency for type Foo" when the bean is POJO but, as soon as I add #Dependent at the top, everything works ok?
I remember it used to work fine without specifying the scope. I think I broke something.
The specs say:
A managed bean is implemented by a Java class, which is called its bean class. A top-level Java class is a managed bean if it is defined to be a managed bean by any other Java EE technology specification, such as the JavaServer Faces technology specification, or if it meets all the following conditions.
It is not a nonstatic inner class.
It is a concrete class or is annotated #Decorator.
It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml.
It has an appropriate constructor. That is, one of the following is the case.
The class has a constructor with no parameters.
The class declares a constructor annotated #Inject.
No special declaration, such as an annotation, is required to define a managed bean.
Sounds like you were used to CDI 1.0 and are now confused by implicit bean archives introduced in CDI 1.1.
beans.xml is now optional, and implicit bean archives are the default, which means that a class is a bean candidate only if it has a bean defining annotation like #Dependent, #RequestScoped etc.
Is there anyway to specify order in which beans to be instantiated? i.e. I want specific beans to be instantiated before other beans, its like startup sequence.
I am using Spring 3.2 and annotation based declaration method.
If bean A depends on bean B by defining <property/>, #Autowired or <constructor-arg/> then the order is forced and fixed by the Spring container. No problem here.
But if you want to enforce specific order of bean creation which is not expressed via explicit dependencies feel free to use:
<bean id="A" depends-on="B"/>
<bean id="B"/>
or better (with annotations, works also with #Bean Java configuration):
#Service
#DependsOn("B")
public class A {}
or even better... don't use it. These constructs are a code smell and often suggest you have some nasty invisible dependency between your components.
Agreed with the answer provided by Tomasz. If you know that bean A depends on bean B then this is right approach.
Sometimes you have logic that should be executed before all beans instantiation. In this case you can use BeanFactoryPostProcessor. Spring creates and executes BeanFactoryPostProcessors first and after that only all other beans. At the same time if your BeanFactoryPostProcessor depends on some bean A you can use property or constructor injection. In this case Spring will create bean A first, then your BeanFactoryPostProcessor, call BeanFactoryPostProcessor and after that only instatiate all other beans in the context.
You can use the Ordered interface on your bean to define ordering relative to other beans.
Further,if you use BeanFactoryPostProcessor as emamedov said, Ordered interface can be implemented to control BeanFactoryPostProcessor instance sequence.
Injecting bean with scope prototype with #Autowired usually doesn't work as expected. But when writing code, it's easy to accidentally inject a prototype.
Is there a way to get a list of all #Autowired fields and methods and to match that with a Spring AppContext to check for this?
One approach could be to override org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor(which is responsible for processing #Autowired, #Inject, #Resource etc) and perform the checks that you have mentioned in this overridden bean post processor. However, AutowiredAnnotationBeanPostProcessor gets registered with quite a few of the common custom namespaces (context:component-scan, context:annotation-config etc), so these custom annotations will have to be replaced with the corresponding bean variation and the overridden post processor also registered as a bean.
I have an interface its 2 implementation. I annotate both implementations by #Component. How can I specific one of them to be the default bean when will be used to inject by #Autowired as default.
Thanks
Use #Primary annotation on the bean which you think given higher priority.
from doc
Indicates that a bean should be given preference when multiple
candidates are qualified to autowire a single-valued dependency. If
exactly one 'primary' bean exists among the candidates, it will be the
autowired value.
May be used on any class directly or indirectly annotated with
Component or on methods annotated with Bean.
Using Primary at the class level has no effect unless
component-scanning is being used. If a Primary-annotated class is
declared via XML, Primary annotation metadata is ignored, and <bean
primary="true|false"/> is respected instead.
Autowired works "by type", meaning it can autowire when exactly one bean matches. When more than one bean matches, use Autowired + Qualifier annotations. Qualifier calls out the name of the bean to autowire.
This means when you declare the Components you need to name them as well.
Which annotation, #Resource (jsr250) or #Autowired (Spring-specific) should I use in DI?
I have successfully used both in the past, #Resource(name="blah") and #Autowired #Qualifier("blah")
My instinct is to stick with the #Resource tag since it's been ratified by the jsr people.
Anyone has strong thoughts on this?
Both #Autowired (or #Inject) and #Resource work equally well. But there is a conceptual difference or a difference in the meaning
#Resource means get me a known resource by name. The name is extracted from the name of the annotated setter or field, or it is taken from the name-Parameter.
#Inject or #Autowired try to wire in a suitable other component by type.
These are two quite distinct concepts. Unfortunately, the Spring-Implementation of #Resource has a built-in fallback, which kicks in when resolution-by-name fails. In this case, it falls back to the #Autowired-kind resolution-by-type. While this fallback is convenient, it causes a lot of confusion, because people are unaware of the conceptual difference and tend to use #Resource for type-based autowiring.
In spring pre-3.0 it doesn't matter which one.
In spring 3.0 there's support for the standard (JSR-330) annotation #javax.inject.Inject - use it, with a combination of #Qualifier. Note that spring now also supports the #javax.inject.Qualifier meta-annotation:
#Qualifier
#Retention(RUNTIME)
public #interface YourQualifier {}
So you can have
<bean class="com.pkg.SomeBean">
<qualifier type="YourQualifier"/>
</bean>
or
#YourQualifier
#Component
public class SomeBean implements Foo { .. }
And then:
#Inject #YourQualifier private Foo foo;
This makes less use of String-names, which can be misspelled and are harder to maintain.
As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:
#Resource allows you to specify a name of the injected bean
#Autowired allows you to mark it as non-mandatory.
The primary difference is, #Autowired is a spring annotation. Whereas #Resource is specified by the JSR-250, as you pointed out yourself. So the latter is part of Java whereas the former is Spring specific.
Hence, you are right in suggesting that, in a sense. I found folks use #Autowired with #Qualifier because it is more powerful. Moving from some framework to some other is considered very unlikely, if not myth, especially in the case of Spring.
I would like to emphasize one comment from #Jules on this answer to this question. The comment brings a useful link: Spring Injection with #Resource, #Autowired and #Inject. I encourage you to read it entirely, however here is a quick summary of its usefulness:
How annotations select the right implementation?
#Autowired and #Inject
Matches by Type
Restricts by Qualifiers
Matches by Name
#Resource
Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)
Which annotations (or combination of) should I use for injecting my beans?
Explicitly name your component [#Component("beanName")]
Use #Resource with the name attribute [#Resource(name="beanName")]
Why should I not use #Qualifier?
Avoid #Qualifier annotations unless you want to create a list of similar beans. For example you may want to mark a set of rules with a specific #Qualifier annotation. This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.
Does bean injection slow my program?
Scan specific packages for components [context:component-scan base-package="com.sourceallies.person"]. While this will result in more component-scan configurations it reduces the chance that you’ll add unnecessary components to your Spring context.
Reference: Spring Injection with #Resource, #Autowired and #Inject
This is what I got from the Spring 3.0.x Reference Manual :-
Tip
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, use 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.
As a specific consequence of this semantic difference, beans that are
themselves defined as a collection or map type cannot be injected
through #Autowired, because type matching is not properly applicable
to them. Use #Resource for such beans, referring to the specific
collection or map bean by unique name.
#Autowired applies to fields, constructors, and multi-argument
methods, allowing for narrowing through qualifier annotations at the
parameter level. By contrast, #Resource is supported only for fields
and bean property setter methods with a single argument. As a
consequence, stick with qualifiers if your injection target is a
constructor or a multi-argument method.
#Autowired + #Qualifier will work only with spring DI, if you want to use some other DI in future #Resource is good option.
other difference which I found very significant is #Qualifier does not support dynamic bean wiring, as #Qualifier does not support placeholder, while #Resource does it very well.
For example:
if you have an interface with multiple implementations like this
interface parent {
}
#Service("actualService")
class ActualService implements parent{
}
#Service("stubbedService")
class SubbedService implements parent{
}
with #Autowired & #Qualifier you need to set specific child implementation
like
#Autowired
#Qualifier("actualService") or
#Qualifier("stubbedService")
Parent object;
which does not provide placeholder while with #Resource you can put placeholder and use property file to inject specific child implementation like
#Resource(name="${service.name}")
Parent object;
where service.name is set in property file as
#service.name=actualService
service.name=stubbedService
Hope that helps someone :)
Both of them are equally good. The advantage of using Resource is in future if you want to another DI framework other than spring, your code changes will be much simpler. Using Autowired your code is tightly coupled with springs DI.
When you analyze critically from the base classes of these two annotations.You will realize the following differences.
#Autowired uses AutowiredAnnotationBeanPostProcessor to inject dependencies.
#Resource uses CommonAnnotationBeanPostProcessor to inject dependencies.
Even though they use different post processor classes they all behave nearly identically.
The differences critically lie in their execution paths, which I have highlighted below.
#Autowired / #Inject
1.Matches by Type
2.Restricts by Qualifiers
3.Matches by Name
#Resource
1.Matches by Name
2.Matches by Type
3.Restricts by Qualifiers (ignored if match is found by name)
With #Resource you can do bean self-injection, it might be needed in order to run all extra logic added by bean post processors like transactional or security related stuff.
With Spring 4.3+ #Autowired is also capable of doing this.
#Resource is often used by high-level objects, defined via JNDI. #Autowired or #Inject will be used by more common beans.
As far as I know, it's not a specification, nor even a convention. It's more the logical way standard code will use these annotations.
As a note here:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext and SpringBeanAutowiringSupport.processInjectionBasedOnServletContext DOES NOT work with #Resource annotation. So, there are difference.