簡體   English   中英

你如何在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";
    }
}

除了官方文檔之外,我發現這篇文章非常適合廣泛地介紹構造型注釋。

注釋不再是MVC特定的。 有關更多信息,請參閱參考文檔 使用@Component注釋或其規范的一個示例是具有監視支持的tcServer 請看這里的例子。 此監視支持添加了加載時間AspectJ編織。

總而言之,注釋可以在Spring容器啟動后的運行時在不同的設置中使用,或者在使用AspectJ編織的編譯/加載時使用。

別忘了在xml上添加這個標簽

    <context:component-scan  base-package="com.example.beans"/> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM