How do you use stereotype annotations in Spring 2.5.x?

topchef picture topchef · Mar 27, 2010 · Viewed 9.7k times · Source

When moving to Spring 2.5.x I found that it adds more stereotype annotations (on top of @Repository from 2.0): @Component, @Service and @Controller. How do you use them? Do you rely on implicit Spring support or you define custom stereotype specific functions/aspects/features? Or is it predominately for marking beans (compile time, conceptual, etc.)?

Answer

seanhodges picture seanhodges · Mar 27, 2010

The following stereotype annotations in 2.5 can be used in a Spring MVC application as an alternative to wiring the beans in XML:

  • @Repository - for DAO beans - allows you to throw DataAccessException when the data source is not available.

  • @Service - for business beans - are fairly simple beans that have some default retention policies set up.

  • @Controller - for servlets - allows you to set up page request mappings, etc.

In addition, a generic fourth annotation has been introduced: @Component. All of the MVC annotations are specialisations of this one, and you can even use @Component on it's own, though by doing this in Spring MVC, you will not make use of any future optimisations/functionality added to the higher-level annotations. You can also extend @Component to create your own custom stereotypes.

Here is a quick example of the MVC annotations in action... First, the data access object:

@Repository
public class DatabaseDAO {
    @Autowired
    private SimpleJdbcTemplate jdbcTemplate;

    public List<String> getAllRecords() {
        return jdbcTemplate.queryForObject("select record from my_table", List.class);
    }
}

The service:

@Service
public class DataService {
    @Autowired
    private DatabaseDAO database;

    public List<String> getDataAsList() {
        List<String> out = database.getAllRecords();
        out.add("Create New...");
        return out;
    }
}

And finally, the controller:

@Controller("/index.html")
public class IndexController {
    @Autowired
    private DataService dataService;

    @RequestMapping(method = RequestMethod.GET)
    public String doGet(ModelMap modelMap) {
        modelMap.put(dataService.getDataAsList());
        return "index";
    }
}

I found this article very good for giving a broad overview of the stereotype annotations, in addition to the official documentation.