Spring Boot简介

Spring Boot是为了简化Spring开发而生,从Spring 3.x开始,Spring社区的发展方向就是弱化xml配置文件而加大注解的戏份。最近召开的SpringOne2GX2015大会上显示:Spring Boot已经是Spring社区中增长最迅速的框架,前三名是:Spring Framework,Spring Boot和Spring Security,这个应该是未来的趋势。

我学习Spring Boot,是因为通过cli工具,spring boot开始往flask(python)、express(nodejs)等web框架发展和靠近,并且Spring Boot几乎不需要写xml配置文件。感兴趣的同学可以根据spring boot quick start这篇文章中的例子尝试下。

学习新的技术最佳途径是看官方文档,现在Spring boot的release版本是1.3.0-RELEASE,相应的参考文档是Spring Boot Reference Guide(1.3.0-REALEASE),如果有绝对英文比较吃力的同学,可以参考中文版Spring
Boot参考指南
。在前段时间阅读一篇技术文章,介绍如何阅读ios技术文档,我从中也有所收获,那就是我们应该重视spring.io上的guides部分——Getting Started Guides,这部分都是一些针对特定问题的demo,值得学习。

Spring Boot的项目结构

com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java

如上所示,Spring boot项目的结构划分为web->service->domain,其中domain文件夹可类比与业务模型和数据存储,即xxxBean和Dao层;service层是业务逻辑层,web是控制器。比较特别的是,这种类型的项目有自己的入口,即主类,一般命名为Application.java。Application.java不仅提供入口功能,还提供一些底层服务,例如缓存、项目配置等等。

例子介绍

本文的例子是取自我的side project之中,日报(report)的查询,试图利用Redis作为缓存,优化查询效率。

知识点解析

1. 自定义配置

Spring Boot允许外化配置,这样你可以在不同的环境下使用相同的代码。你可以使用properties文件、yaml文件,环境变量和命令行参数来外化配置。使用@Value注解,可以直接将属性值注入到你的beans中。

Spring Boot使用一个非常特别的PropertySource来允许对值进行合理的覆盖,按照优先考虑的顺序排位如下:

1. 命令行参数
2. 来自java:comp/env的JNDI属性
3. Java系统属性(System.getProperties())
4. 操作系统环境变量
5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource
6. 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量)
7. 在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量)
8. 在@Configuration类上的@PropertySource注解
9. 默认属性(使用SpringApplication.setDefaultProperties指定)

使用场景:可以将一个application.properties打包在Jar内,用来提供一个合理的默认name值;当运行在生产环境时,可以在Jar外提供一个application.properties文件来覆盖name属性;对于一次性的测试,可以使用特病的命令行开关启动,而不需要重复打包jar包。

具体的例子操作过程如下:

  • 新建配置文件(application.properties)

    spring.redis.database=0
    spring.redis.host=localhost
    spring.redis.password= # Login password of the redis server.
    spring.redis.pool.max-active=8
    spring.redis.pool.max-idle=8
    spring.redis.pool.max-wait=-1
    spring.redis.pool.min-idle=0
    spring.redis.port=6379
    spring.redis.sentinel.master= # Name of Redis server.
    spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
    spring.redis.timeout=0
  • 使用@PropertySource引入配置文件
    @Configuration
    @PropertySource(value = "classpath:/redis.properties")
    @EnableCaching
    public class CacheConfig extends CachingConfigurerSupport {
    ......
    }
  • 使用@Value引用属性值
    @Configuration
    @PropertySource(value = "classpath:/redis.properties")
    @EnableCaching
    public class CacheConfig extends CachingConfigurerSupport {
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    ......
    }

2. redis使用

  • 添加pom配置

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    </dependency>
  • 编写CacheConfig
    @Configuration
    @PropertySource(value = "classpath:/redis.properties")
    @EnableCaching
    public class CacheConfig extends CachingConfigurerSupport {
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
    return new KeyGenerator() {
    @Override
    public Object generate(Object target, Method method, Object... params) {
    StringBuilder sb = new StringBuilder();
    sb.append(target.getClass().getName());
    sb.append(method.getName());
    for (Object obj : params) {
    sb.append(obj.toString());
    }
    return sb.toString();
    }
    };
    }
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory();
    factory.setHostName(host);
    factory.setPort(port);
    factory.setTimeout(timeout); //设置连接超时时间
    return factory;
    }
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    // Number of seconds before expiration. Defaults to unlimited (0)
    cacheManager.setDefaultExpiration(10); //设置key-value超时时间
    return cacheManager;
    }
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
    template.afterPropertiesSet();
    return template;
    }
    private void setSerializer(StringRedisTemplate template) {
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    }
    }
  • 启动缓存,使用@Cacheable注解在需要缓存的接口上即可
    @Service
    public class ReportService {
    @Cacheable(value = "reportcache", keyGenerator = "wiselyKeyGenerator")
    public ReportBean getReport(Long id, String date, String content, String title) {
    System.out.println("无缓存的时候调用这里---数据库查询");
    return new ReportBean(id, date, content, title);
    }
    }
  • 测试验证

参考资料

  1. spring boot quick start
  2. Spring Boot参考指南
  3. Spring Boot Reference Guide(1.3.0-REALEASE)
  4. Getting Started Guides
  5. Caching Data in Spring Using Redis
  6. Spring boot使用Redis做缓存
  7. redis设计与实现
文/杜琪(简书作者)

原文链接:http://www.jianshu.com/p/a2ab17707eff

著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

Spring Boot简介的更多相关文章

  1. Spring Boot从入门到精通之:一、Spring Boot简介及快速入门

    Spring Boot Spring Boot 简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来 ...

  2. Spring Boot基础:Spring Boot简介与快速搭建(1)

    1. Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的创建.运行.调试.部署等. Spring Boot默认使用tomca ...

  3. Spring Boot 简介

    作者其他Spring系列文章 Spring Framework简介 Spring框架快速入门  Spring Boot愿景 Spring Boot愿景就是让我们创建可运行的.独立的.基于Spring的 ...

  4. Sping Boot入门到实战之入门篇(一):Spring Boot简介

    该篇为Spring Boot入门到实战系列入门篇的第一篇.对Spring Boot做一个大致的介绍. 传统的基于Spring的Java Web应用,需要配置web.xml, applicationCo ...

  5. Spring Boot学习——Spring Boot简介

    最近工作中需要使用到Spring Boot,但是以前工作中没有用到过Spring Boot,所以需要学习下Spring Boot.本系列笔记是笔者学习Spring Boot的笔记,有错误和不足之处,请 ...

  6. 第一章spring boot简介

    接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用Spring Boot来让你更易上手, ...

  7. 什么是Spring Boot简介

    1.什么是spring boot 简单的说,spring boot就是整合了很多优秀的框架,不用我们自己手动的去写一堆xml配置然后进行配置. 从本质上来说,Spring Boot就是Spring,它 ...

  8. Spring Boot 简介与入门(2.1.6版)

    Spring Boot 2.1.6 版       与时俱进是每一个程序员都应该有的意识,当一个Java程序员在当代遍布的时候,你就该意识到能多学点什么.可观的是后端的框架是稳定的,它们能够维持更久的 ...

  9. 【Spring Boot学习之一】Spring Boot简介

    环境 Java1.8 Spring Boot 1.3.2 一.Spring Boot特点1.使用java运行项目,内置tomcat,无需外部容器:2.减少XML配置,使用properties文件和注解 ...

随机推荐

  1. 关于cell中添加子视图 复用重叠问题的解决方法

    问题本质:   因为你要添加的子视图并不是在自定义的cell中实现的,而是根据系统给的UITableViewCell这个类创建的实例,每次进图 cellForRow方法都会创建一个cell,每次都要创 ...

  2. 对于System.Net.Http的学习(一)——System.Net.Http 简介(转)

    最新在学习System.Net.Http的知识,看到有篇文章写的十分详细,就想转过来,自己记录下.原地址是http://www.cnblogs.com/chillsrc/p/3439215.html? ...

  3. BZOJ 2819: Nim( nim + DFS序 + 树状数组 + LCA )

    虽然vfleaking好像想卡DFS...但我还是用DFS过了... 路径上的石堆异或和=0就是必败, 否则就是必胜(nim游戏). 这样就变成一个经典问题了, 用DFS序+BIT+LCA就可以在O( ...

  4. 学习PS必须弄懂的专业术语

    在学习PS的过程中,我们经常会遇到一些专业术语,下面我们来对一些常用的.比较难理解的术语进行简单讲解. 像素:像素是构成图像的最基本元素,它实际上是一个个独立的小方格,每个像素都能记录它所在的位置和颜 ...

  5. 搭建Hadoop集群 (二)

    前面的步骤请看  搭建Hadoop集群 (一) 安装Hadoop 解压安装 登录master, 下载解压hadoop 2.6.2压缩包到/home/hm/文件夹. (也可以从主机拖拽或者psftp压缩 ...

  6. mysql查询结果写入文件

    注:转自csdn zuyi532 方法1: shell> mysql -uroot -proot -h localhost xxx库 -e " select * from xxx表 l ...

  7. Django Web开发【2】Django入门

    配置开发环境 1.安装Python,我使用的是centos 6.0,python版本为2.6.6 2.安装Django,Django版本为1.3.5 在Django官网下载对应版本之后,解压压缩包,进 ...

  8. R与数据分析旧笔记(十六) 基于密度的方法:DBSCAN

    基于密度的方法:DBSCAN 基于密度的方法:DBSCAN DBSCAN=Density-Based Spatial Clustering of Applications with Noise 本算法 ...

  9. 《JavaScript+DOM编程艺术》的摘要(三)---图片库实例

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...

  10. 静态资源库CDN服务

    使用静态资源库可以访问线上资源文件,比如jquery库.bootstrap库.使用百度静态资源库的居多,但是发现百度暂时不支持https协议,bootcdn是一个不错的选择. 百度静态资源公共库 优点 ...