![](/img/trans.png)
[英]How do I inject a single property value into a string using spring 2.5.x?
[英]How do you use stereotype annotations in Spring 2.5.x?
迁移到Spring 2.5.x时,我发现它添加了更多的构造型注释(在2.0的@Repository之上): @ Component,@ Service和@Controller 。 你怎么用它们? 您是否依赖于隐式Spring支持或您定义自定义构造型特定函数/方面/功能? 或者它主要用于标记bean(编译时,概念等)?
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);
}
}
服务:
@Service
public class DataService {
@Autowired
private DatabaseDAO database;
public List<String> getDataAsList() {
List<String> out = database.getAllRecords();
out.add("Create New...");
return out;
}
}
最后,控制器:
@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";
}
}
别忘了在xml上添加这个标签
<context:component-scan base-package="com.example.beans"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.