In here I showed how to use the @Named with Spring 3 to create “named beans”, to be used in frameworks like JSF2… Since we usually want to inject service implementations into our JSF beans, we need to use the @Inject from the JSR 330 (of course the regular Spring DI mechanism works as well). The JSF bean could look like:
@Model public class SimpleBean { @Inject Service service; ... public void callSomething() { service.myStuff(); ...
Now we need to have an implementation of the Service interface. In order to allow the Spring Framework to find the (right) implementation the class itself needs to be annotated with the @Component annotation (or one of its specializations, like @Service which marks the class to be a “business service facade”):
@org.springframework.stereotype.Service public class ServiceImpl implements Service { ... }
If your class (->interface implementation) does not have a meaning like that, you could simply use the @Named annotation from the JSR 330, like:
@javax.inject.Named public class ServiceImpl implements Service { ... }
The good news with @Named and Spring here is that you could also combine the “Component” annotations and the @Named. This is useful if you have multiple implementations, like:
@org.springframework.stereotype.Service @javax.inject.Named("bonusCustomerSerivce") public class ServiceImpl implements Service { ... }
The injection point inside of your “clients”, like the JSF managed beans now also need to use @Named(“bonusCustomerService”) if the bean wants to use this specific one. The @Named usage may look a bit verbose, but there is help. You could create your own annotations, leveraging the @Qualifier from JSR 330. This is also supported in Spring3…
Good news here is (again) that most of the Dependency Injection “API” is similar in JavaEE 6 and Spring 3. You can used the @Inject, @Named and/or custom @Qualifiers (more soon). Right, there are also some differences between the two, but that’s coming in a later post…
[…] Scopes with Spring 3 6 05 2010 With the advent of Spring 3 the framework now supports the Java Injection standard (JSR 330). However, unfortunately, they do not support the scoping, which is introduced in Java EE […]
Thanks Matthias, that was helpful. I like the @Named concept and we will try to use in in Eclipse 4.
U r welcome 🙂