现代化Spring开发与背后的魔法

来源:互联网 发布:java网页游戏开发教程 编辑:程序博客网 时间:2024/04/29 08:00

目录

  • 构建工程
  • 代码编写
  • Spring autowired的魔法
  • Spring-data-jpa的魔法

Spring已经支持xml,annotation,java三种配置方法,在看了一遍文档后,我对注解的方式更偏爱一点。基于注解配置有几个好处

  • 一目了然,直接通过Java Class就可以看出spring是如何装配这个类的
  • 方便快捷,我一直觉得xml很难阅读,Java api用来做“配置”这个工作又显得大材小用

1. 构建工程

PS:可以通过 https://github.com/MoonShining/modern-spring-web-example 下载整个工程

  1. 通过spring官方的生成器,加入web和jpa两个组件,直接生成项目骨架
  2. 导入项目到idea中,通过maven安装依赖
  3. 随便配置一下application.properties
#application.properties文件#jdbc datasource#数据源的基本配置spring.datasource.url=jdbc:mysql://127.0.0.1:3306/java?useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver#tomcat的连接配置,随个人的机器的配置来设定值spring.datasource.tomcat.max-wait=10000spring.datasource.tomcat.max-active=50000spring.datasource.tomcat.test-on-borrow=true# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)spring.jpa.database=MYSQL#该配置自动检查实体和数据库表是否一致,如果不一致则会进行更新数据库表,spring.jpa.hibernate.ddl-auto=update#显示sql语句spring.jpa.show-sql=true# EMBEDDED SERVER CONFIGURATION (ServerProperties)#服务器访问端口设置server.port=8080

这样开发环境就准备好了,开始领略Spring的黑魔法吧!

2.代码编写

定义Model
@Entitypublic class Post {    @Id    @GeneratedValue(strategy= GenerationType.AUTO)    private Long id;    private String title;    private String content;    public Post(String title, String content) {        this.title = title;        this.content = content;    }    ...省略getter setter方法
Dao
public interface PostReporsitory extends CrudRepository<Post, Long> {}
创建Controller
@RestControllerpublic class PostsController {    @Autowired    PostReporsitory repo;    @RequestMapping(method = RequestMethod.GET, value = "/posts/{id}")    public Post post(@PathVariable int id){        String title = "Post %d";        Post p = new Post(String.format("Post %d", id), "body");        repo.save(p);        Post post = repo.findOne(p.getId());        return post;    }}

在这个Controller中,我们保存Post对象,再把它查询出来展示。是不是觉得一头雾水,我们根本没有编写任何Dao层的操作法方法,但是却工作的很好!

这就是spring-data-jpa带来的开发效率上质的提升,我们只需要去extends CrudRepository,剩下的事就不用关心了,spring会自动帮我们生成查询方法!

...repo.save(p);...repo.findOne(p.getId()) 

在这三段简洁的代码中,我最欣赏的有两点。第一是通过反射自动注入PostRepository变量

    @Autowired    PostReporsitory repo;

其次是spring-data-jpa带来的快捷的Dao层操作,比什么MyBatis不知道高到哪里去了。以绝大多数的场景来看,根本用不着去手写sql,而所谓hibernate的性能差问题,那只是用的人水平太低。

Spring autowired的魔法

直接看http://blog.csdn.net/mack415858775/article/details/47721909 这篇文章吧
待续…

Spring-data-jpa的魔法

待续…