1. Overview

In this tutorial, we’ll investigate the usage of JSR-330 annotations with Spring. We’ll look at the @Inject, @Named, and @ManagedBean annotations.

2. Bean Definition with @Named

Let’s first look at how we can define a bean with @Named.

The @Named annotation plays the role of @Component:

@Named
public class JsrPersonRepository {
    // Implementation details
}

Here, we’re annotating the JsrPersonRepository class with @Named. As a result, Spring registers it as a bean.

3. Bean Definition with @ManagedBean

Now, we’ll continue with the @ManagedBean annotation which also marks a class as a bean:

@ManagedBean
public class EmployeeService {
     // Implementation details
}

Similar to @Named, Spring registers the @ManagedBean annotated classes as beans.

4. Bean Wiring with @Inject

Now that we’ve defined our beans using @Bean or @ManagedBean, we’ll look at next how we can define the bean dependencies.

For this purpose, we’ll use the @Inject annotation which has similar behavior with @Autowired.

Firstly, we’ll try the constructor injection:

@Named
public class JsrConstructorInjectionPersonService {

    private final PersonRepository personRepository;

    @Inject
    public JsrConstructorInjectionPersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
}

Secondly, we’ll look at the setter injection:

@Named
public class JsrSetterInjectionPersonService {

    private PersonRepository personRepository;

    @Inject
    public void setPersonRepository(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
}

Lastly, we’ll see the field injection:

@Named
public class JsrFieldInjectionPersonService {

    @Inject
    private PersonRepository personRepository;
}

Next, let’s look at how we can qualify our beans during the injection.

We’ll first name our bean with the @Named annotation:

@Named("department")
public class DepartmentRepository {
}

Here, we’re using the value of @Named to name our bean. As a result, Spring will register DepartmentRepository under the name of department.

Then, we’ll again use @Named for qualification:

@Named
public class DepartmentService {

    private final DepartmentRepository departmentRepository;

    @Inject
    public DepartmentService(@Named("department") DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;
    }
}

Here, we’re using @Inject to trigger the auto-wiring process. Also, we’re using @Named(“department”) to qualify the DepartmentRepository bean.

5. Summary

In this tutorial, we’ve investigated how we can use JSR-330 annotations with Spring.

Finally, check out the source code over on Github.

Leave a Reply

Close Menu