当移到Spring2.5.x时,我发现它添加了更多的原型注释(在2.0版的@Repository之上):@Component、@Service和@Controller。你是怎么用的?您是依赖于隐式Spring支持还是定义了自定义原型特定的函数/方面/特性?还是主要用于标记bean(编译时间、概念等)?
发布于 2010-03-27 07:40:45
在Spring应用程序中,可以使用2.5中的以下原型注释来替代XML中的bean连接:
此外,还引入了一个通用的第四个注释:@Component。所有的MVC注释都是这个注释的特长,您甚至可以自己使用@Component,尽管通过在Spring中这样做,您将不会使用将来添加到更高级别注释中的任何优化/功能。您还可以扩展@组件以创建您自己的自定义原型。
下面是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";
}
}
发布于 2010-03-30 09:37:48
发布于 2010-03-30 01:08:17
不要忘记在xml上添加这个标记。
<context:component-scan base-package="com.example.beans"/>
https://stackoverflow.com/questions/2529781
复制相似问题