代码之家  ›  专栏  ›  技术社区  ›  topchef

如何在Spring2.5.x中使用原型注释?

  •  11
  • topchef  · 技术社区  · 16 年前

    从2.0开始): @组件,@服务 @控制器 . 如何使用它们?您是依赖于隐式Spring支持还是定义了定制的特定于原型的函数/方面/特性?或者它主要用于标记bean(编译时、概念等)?

    3 回复  |  直到 16 年前
        1
  •  13
  •   seanhodges    16 年前

    在SpringMVC应用程序中,可以使用2.5中的以下原型注释来替代XML中的Bean:

    • 您需要在以下情况下引发DataAccessException 数据源不可用。

    • @服务-针对业务bean- 是相当简单的豆子 设置默认保留策略。

    • @控制器-用于servlet- 映射等。

    此外,还引入了通用的第四个注释:@Component。所有的MVC注释都是这个注释的专门化,您甚至可以自己使用@Component,尽管在springmvc中这样做,您将不会使用将来添加到更高级注释中的任何优化/功能。您还可以扩展@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";
        }
    }
    

    this article 除了 official documentation .

        2
  •  3
  •   Espen    16 年前

    注释不再是MVC特有的了。看到了吗 reference documentation 更多信息。使用@Component注释或其规范的一个例子是 tcServer here 举个例子。这个监视支持是通过加载时AspectJ weaving添加的。

    总之,在Spring容器启动后的运行时,或者在编译/加载时使用AspectJ编织时,可以在不同的设置中使用注释。

        3
  •  0
  •   bassem    16 年前

    别忘了在xml上添加这个标记

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