[英]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.