SSH框架特例实战【一】(SpringMVC…

来源:互联网 发布:小额贷款骗局知乎 编辑:程序博客网 时间:2024/06/09 21:02
为啥我把SpringMVC+Spring带上了Hibernate而不是Mybatis?
一是为了练手:既然Spring是粘合剂,那么我自然可以改改系统构架了对吧?(可以检验是否理解原理)
知识准备:
首先这3个框架单独的实现得走一遍吧——详见连接
里面有2个关键的工程实现:
SpringMVC(也就是SpringMVC+Spring框架)
Spring+Hibernate(SH框架的整合)

自然而然的,三个框架组合在一起,就是:
SSH框架特例实战【一】(SpringMVC+Spring+Hibernate)  把相应的文件考过来,把相应的xml代码整合在一起,OK!
  这里用的SpringMVC框架,选择了最简单的形式。而Spring+Hibernate那个工程文件中,稍微复杂点,需要在main函数里载入ApplicationContext.xml(也就是装满beans豆豆的给Spring框架用的配置文件)
  首先我们复习一遍:
  在SH框架中,Spring已经接管了本应属于Hibernate.cfg.xml的配置工作。我们可以看到,相比最纯粹的Hibernate单独实现,Spring接管后的Hibernate.cfg.xml配置文件已经非常简洁。然后我们就在main函数里启动Spring,接着用getBean来获得实际的应用。
  而在SpringMVC中(实际就是SpringMVC+Spring,因为二者天然相辅相成),Spring接管了各种资源调度。哪些目录被映射成静态视图、哪些被映射成动态地址、哪个目录被自动扫描成beans、哪里存的jsp作为SpringMVC要用的view……等等。配置完后我们就可以安心地写webApp了。
  然后问题出现了
  在SH我们是自己启动Spring的,有个context可以用
  在SpringMVC是自动启动Spring的,context实例在哪儿
  换句话说,我们在SpringMVC里怎么用context来获取hibernate的服务?或者说Dao服务?

  让我们推理下。既然Spring是自动启动的,那么肯定有个context在程序某个地方。Spring是管理各种beans的,那么如果一个服务注册为beans,就能通过getBean方法获取了。getBean……又是getBean,我需要一个实例才能调用getBean方法。或者说,压根就不需要我来调用?
  没错,Spring给你自动“注入”。怎么注入呢?这里列出关键的对比代码:

在SH框架中,我们是这么调用服务的:
ApplicationContextcontext;
       context =newClassPathXmlApplicationContext("configuration/applicationContext.xml");

       DataSourcedataSource = (DataSource)context.getBean(DataSource.class);
      System.out.println("dataSource.toString()=="+dataSource);

      
      BookService bookService;
      bookService = context.getBean(BookService.class);
      bookService.saveBook(new Book(1, "Android源码分析", "1002", 45,10));
      bookService.saveBook(new Book(2, "iOS源码分析", "1012", 43,20));
      
       StringbookName = bookService.findBookById(1);
      System.out.println(bookName);

而在SpringMVC中,如果要调用BookService,我们直接用个标签就好:
importdao_service.BookService;
importjavax.annotation.Resource;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.servlet.ModelAndView;

@Controller
public class HiFirstApp{
   @Resource  //这里是正解
   private BookService bookService;
   
   @RequestMapping(value="/helloworld/index",method = {RequestMethod.GET})
   public ModelAndView index(){
      
       //直接调用hibernate代码,发觉少了context
       //bookService =context.getBean(BookService.class);//???
       StringbookName = bookService.findBookById(1);
      System.out.println(bookName);
      
      
      ModelAndView modelAndView = new ModelAndView(); 
      modelAndView.addObject("message", "Hello World! HelloSpringMVC2"+bookName);  
      modelAndView.setViewName("index");
       returnmodelAndView;
   }
}

看到了吗?我们只需要在类里面建立一个私有变量bookService,外加注释@Resource就可以了
于是这个注册了网址的服务,在你输入连接的时候,他就会自动调用Spring去生成应该生成的bookService
结果就是:
SSH框架特例实战【一】(SpringMVC+Spring+Hibernate)






0 0
原创粉丝点击