When moving to Spring 2.5.x I found that it adds more stereotype annot开发者_如何学运维ations (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.)?
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.
The annotations isn't MVC specific anymore. See the reference documentation for more information. An example of using the @Component annotation or a specification of it is the tcServer with its monitoring support. See here for an example. This monitoring support is added with load-time AspectJ weaving.
Summarized, the annotations can be used in different settings at runtime after the Spring container is started, or at compile/load-time with AspectJ weaving.
dont forget to add this tag on xml
<context:component-scan base-package="com.example.beans"/>
精彩评论