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

目录
  • 构建工程
  • 代码编写
  • 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=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#tomcat的连接配置,随个人的机器的配置来设定值
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50000
spring.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
@Entity
public 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
@RestController
public 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的魔法

待续…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值