你如何在Spring 2.5.x中使用构造型注释?

top*_*hef 11 java spring annotations aspects stereotype

迁移到Spring 2.5.x时,我发现它添加了更多的构造型注释(在2.0 的@Repository之上):@ Component,@ Service@Controller.你怎么用它们?您是否依赖于隐式Spring支持或您定义自定义构造型特定函数/方面/功能?或者它主要用于标记bean(编译时,概念等)?

sea*_*ges 13

2.5中的以下构造型注释可以在Spring MVC应用程序中使用,作为在XML中连接bean的替代方法:

  • @Repository - 对于DAO bean - 允许您在数据源不可用时抛出DataAccessException.

  • @Service - 用于业务bean - 是相当简单的bean,它们设置了一些默认保留策略.

  • @Controller - 用于servlet - 允许您设置页面请求映射等.

此外,还引入了通用的第四个注释:@Component.所有MVC注释都是这个注释的特殊化,你甚至可以自己使用@Component,但是在Spring MVC中这样做,你将不会使用任何未来的更高级别注释的优化/功能.您还可以扩展@Component以创建自己的自定义构造型.

以下是MVC注释的快速示例...首先,数据访问对象:

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

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

服务:

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

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

最后,控制器:

@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";
    }
}
Run Code Online (Sandbox Code Playgroud)

除了官方文档之外,我发现这篇文章非常适合广泛地介绍构造型注释.