Spring 3.0 and JSR 330: Using @Inject

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…

About these ads

3 thoughts on “Spring 3.0 and JSR 330: Using @Inject

  1. Pingback: Using CDI Scopes with Spring 3 « Matthias Wessendorf's Weblog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s