SpringBoot的基本配置

一、Spring Boot基本配置

1、入口类和@SpringBootApplication

Spring Boot通常有一个名为*Application的入口类,入口类中有一个main方法,这个main方法其实就是一个标准的Java应用程序的入口方法。在main方法中使用SpringApplication.run(Chapter01Application.class, args),启动Spring Boot应用项目。

2、关闭特定的自动配置

通过@SpringBootApplication源码可以看出,关闭特定的自动配置应该使用@SpringBootApplication注解的exclude参数,例如:
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

3、定制Banner

在Spring Boot启动的时候会有一个默认启动图案,这个图案是可以自定义的。
1)我们在src/main/resources下新建一个banner.txt
2)通过http://patorjk.com/software/taag网站生成字符,将生成的字符复制到banner.txt文件中
3)自动程序,这时控制台图案将变成刚才生成的图案

4、关闭banner

在main方法中修改为(Spring Boot:1.4.0):

    SpringApplication application = new SpringApplication(Chapter1Application.class);
    application.setBannerMode(Mode.OFF);
    application.run(args);

或者

    new SpringApplicationBuilder(Chapter1Application.class) //
                .bannerMode(Mode.OFF) //
                .run(args);

5、Spring Boot配置文件

Spring Boot使用一个全局的配置文件application.properties或application.yml,放置在src/main/resources目录或者类路径的/config下。<p>
Spring Boot不仅支持常规的properties配置文件,还支持yaml语言的配置文件。yaml是以数据为中心的语言,在配置数据的时候具有面向对象的特征。<p>
Spring Boot的全局配置文件的作用是对一些默认配置值进行修改。

例如:

修改tomcat端口为8080->8888,默认的访问路径为"/"->”/helloboot”。可以在
application.properties中添加:

    server.port=9090
    server.context-path=/helloBoot

6、官方starter pom

<div style="color:gray">
spring-boot-starter      Spring Boot核心starter,包含自动配置、日志、yaml配置文件的支持

spring-boot-starter-actuator       准生产特性,用来监控和管理应用

spring-boot-starter-remote-shell       提供基于ssh协议的监控和管理

spring-boot-starter-amqp       使用spring-rabbit来支持AMQP

spring-boot-starter-aop       使用spring-aop和AspectJ支持面向切面变成

spring-boot-starter-batch       对Spring Batch的支持

spring-boot-starter-cache       对Spring Cache抽象的支持

spring-boot-starter-cloud-connectors       对云平台(Cloud Foundry,Heroku)提供的服务提供简化的连接方法

spring-boot-starter-data-elasticsearch       通过spring-data-elasticsearch对Elasticsearch的支持

spring-boot-starter-data-gemfire       通过spring-data-gemfire对分布式存储GenFile的支持

spring-boot-starter-data-jpa       对JPA的支持,包含spring-data-jpa,spring-orm和Hibernate

spring-boot-starter-data-mongodb       通过spring-data-mongodb,对MongoDB进行支持

spring-boot-starter-data-rest       通过spring-data-rest-webmvc将Spring Data Repository暴露REST形式的服务

spring-boot-starter-data-solr       通过spring-data-solr对Apache Solr数据检索平台的支持

spring-boot-starter-freemarker       对FreeMarker模板引擎的支持

spring-boot-starter-groovy-templates       对Groovy模板引擎的支持

spring-boot-starter-hateoas       通过spring-hateoas 通过spring-hateoas对基于HATEOAS的REST形式的网络服务的支持

spring-boot-starter-hornetq       通过HornetQ对JMS的支持

spring-boot-starter-integration       对系统集成框架spring-integration的支持

spring-boot-starter-jdbc       对JDBC数据库的支持

spring-boot-starter-jersey       对Jersery REST形式的网络服务的支持

spring-boot-starter-jta-atomikos       通过Atomikos对分布式事务的支持

spring-boot-starter-jta-bitronix       通过Bitronix对分布式事务的支持

spring-boot-starter-mail       对javax.mail的支持

spring-boot-starter-mobile       对spring-mobile的支持

spring-boot-starter-mustache       对Mustache模板引擎的支持

spring-boot-starter-redis       对键值对内存数据库Redis的支持,包含spring-reids

spring-boot-starter-security       对spring-security的支持

spring-boot-starter-social-faceboot       通过spring-social-faceboot对Facebook的支持

spring-boot-starter-social-twitter       通过spring-social-twitter对Twitter的支持

spring-boot-starter-test       对常用的测试框架Junit,Hamcrest和Mockito的支持,包含spring-test模板

spring-boot-starter-thymeleaf       对Thymeleaf模板引擎的支持,包含于Spring整合的配置

spring-boot-starter-velocity       对Velocity模板引擎的支持

spring-boot-starter-web       对Web项目开发的支持,包含Tomcat和spring-webmvc

spring-boot-starter-Tomcat       Spring Boot默认的Servlet容器Tomcat

spring-boot-starter-Jetty       使用Jetty作为Servlet容器替换Tomcat

spring-boot-starter-undertow       使用Undertow作为Servlet容器替换Tomcat

spring-boot-starter-logging       Spring Boot默认的日志框架Logback

spring-boot-starter-log4j       支持使用Log4j日志框架

spring-boot-starter-websocket       对WebSocket开发的支持

spring-boot-starter-ws      对Spring Web Services的支持

</div>
<p>
还有第三方为Spring Boot所写的starter pom,这里不做介绍

7、使用xml配置

Spring Boot提倡零配置,即无xml配置,但是在实际项目中,可能有些特殊要求,使得开发者必须使用xml配置,这时我们可以通过Spring提供的@ImportResource来加载xml配置,例如:

    @ImportResource({"classpath:context.xml”})

8、命令行参数配置

Spring Boot可以是基于jar包运行的,打成jar包的程序可以直接通过java -jar xx.jar来运行
可以通过java -jar xx.jar —server.port=8888来修改Tomcat端口号

9、常规属性配置

在常规Spring环境下,注入properties文件里的值得方式,通过@PropertySource指明properties文件的位置,然后通过@Value注入值。在Spring Boot里,只需要在application.properties定义属性,直接使用@Value注入即可。

例如:

在application.properties文件中添加属性:

     book.author=cm
     book.name=spring boot

在com.gnd.springboot.config.init路径下新建PropertiesTests属性配置类,使用@Value注入book属性

    @Component
    public class PropertiesTests {
        @Value("book.author")
        private String author;
        @Value("book.name")
        private String name;
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

10、类型安全的配置(基于properties)

Spring Boot提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全的配置。所以,常规属性配置可以修改为:

    @Component
    @ConfigurationProperties(prefix = "book")
    public class PropertiesTests {
        private String author;
        private String name;
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

11、日志配置

Spring Boot支持Java Util Logging、Log4J、Log4J2和Logback作为日志框架,无论使用哪种日志框架,Spring Boot已为当前使用日志框架的控制台输出及文件输出做好了配置。<p>
默认情况下,Spring Boot使用Logback作为日志框架。日志级别:****logging.file=/home/cm/mylog.log****
配置日志文件,格式为logging.level.包名=级别:****logging.level.org.springframework.web=DEBUG****

12、Profile配置

Profile是Spring用来针对不同的环境对不同的配置提供支持的,全局Profile配置使用application-{profile}.properties(如application-prod.properties),
通过在application.properties中设置****spring.profiles.active=prod****来指定活动的Profile
例如:

我们分为生产(prod)和开发(dev)环境,在生产环境下端口号为80,开发环境为8888。

两种配置文件分别为:

    application-prod.properties:  server.port=80
    application-dev.properties:  server.port=8888

然后在application.properties增加:

    spring.profiles.active=dev(prod)

通过Profile可以灵活切换Spring Boot项目的配置了。

二、Spring Boot运行原理

Spring Boot关于自动配置的源码在spring-boot-autoconfigure-1.4.0.RELEASE.jar内,主要包含了以下配置:<p>
<a href="http://i1.piimg.com/4851/bb6e18a430a22a09.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/bb6e18a430a22a09t.jpg"></a>
<a href="http://i1.piimg.com/4851/73ed190dbda257cb.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/73ed190dbda257cbt.jpg"></a><p>
若想知道Spring Boot为我们做了哪些自动配置,可以通过通过三种方式查看以启用和未启用的自动配置的报告:<p>
1)运行jar时增加—debug参数:java -jar xx.jar —debug<p>
2)在application.properties中设置属性:debug=true(这个方便点)<p>
3)在开发工具启动参数中配置<p>
<a href="http://i1.piimg.com/4851/db0610f744b512ec.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/db0610f744b512ect.jpg"></a><p>

1、Spring Boot运行原理解析:

对@SpringBootApplication注解说明:
@SpringBootApplication是一个组合注解,它的核心功能是由@EnableAutoConfiguration注解提供的。
查看@EnableAutoConfiguration源码<p>
<a href="http://i1.piimg.com/4851/df2b568388d67082.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/df2b568388d67082t.jpg"></a><p>
这里@Import注解导入配置功能,EnableAutoConfigurationImportSelector使用SpringFactoriesLoader.loadFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包,而spring-boot-autoconfigure-1.4.0.RELEASE.jar里就有一个spring.factories文件,次问价中声明了有哪些自动配置。
<a href="http://i1.piimg.com/4851/8290194ff6bbbda5.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/8290194ff6bbbda5t.jpg"></a>

<a href="http://i1.piimg.com/4851/dba6c685c8097175.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/dba6c685c8097175t.jpg"></a><p>
​ 任意打开一个AutoConfiguration文件,一般都有以下条件注解,在spring-boot-autoconfigure-1.4.0.RELEASE.jar的org.springframework.boot.autoconfigure.condition包下,条件注解如下:<p>
<div style="color:gray">
@ConditionalOnBean:       当容器里有指定的Bean的条件下

@ConditionalOnClass:       当类路径下有指定的类的条件下

@ConditionalOnExpression:       基于SpEL表达式作为判断条件

@ConditionalOnJava:       基于JVM版本作为判断条件

@ConditionalOnJndi:       在JNDI存在的条件下查找指定的位置

@ConditionalOnMissingBean:       当容器里没有指定Bean的情况下

@ConditionalOnMissingClass:       当类路径下没有指定的类的条件下

@ConditionalOnNotWebApplication:       当前项目不是Web项目的条件下

@ConditionalOnProperty:       指定的属性是否有指定的值

@ConditionalOnResource:       类路径是否有指定的值

@ConditionalOnSingleCandidate:       当指定Bean在容器中只有一个,或者虽然有多个但是指定首选的Bean

@ConditionalOnWebApplication:       当前项目是Web项目的条件下

</div><p>
这些注解都是使用了@Conditional元注解,不过是使用了不同的条件而已。

2、分析http的编码配置

配置参数

HttpEncodingProperties的源码如下:<p>
<a href="http://i1.piimg.com/4851/01b5f66dfd191b68.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/01b5f66dfd191b68t.jpg"></a><p>
这里的配置类可以直接在application.properties中以spring.http.encoding 为前缀配置,比如:如果需要修改默认编码方式,可通过spring.http.encoding.charset=gbk 配置。
根据条件配置CharacterEncodingFilter的Bean,源码如下:
<a href="http://i1.piimg.com/4851/6307e6e411a78c22.png" title="点击显示原始图片"><img src="http://i1.piimg.com/4851/6307e6e411a78c22t.jpg"></a>

3、自定义自动配置(包装成starter pom)

1)新建maven工程spring-boot-starter-hello,在pom.xml中添加如下配置:

    <properties>
        <spring-framework.version>1.4.0.RELEASE</spring-framework.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
    </dependencies>
  1. 新建属性配置类HellpServiceProperties
    @ConfigurationProperties(prefix = "hello")
    public class HelloServiceProperties {
        private static final String MSG = "world";
        private String msg = MSG;
        public String getMsg() {
            return msg;
        }
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

此种配置方式为类型安全的属性获取。在application.properties中通过hello.msg= 来设置,若不设置,默认为hello.msg=world<p>

3)新建依据类HelloService(此类可以是第三方类库的类)

    public class HelloService {
        private String msg;
        public String sayHello() {
            return "Hello " + msg;
        }
        public String getMsg() {
            return msg;
        }
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

4)新建自动配置类

    @Configuration
    @EnableConfigurationProperties(HelloServiceProperties.class)
    @ConditionalOnClass(HelloService.class)
    @ConditionalOnProperty(prefix = "hello", value = "enabled", matchIfMissing = true)
    public class HelloServiceAutoConfiguration {
        @Autowired
        private HelloServiceProperties helloServiceProperties;
        @Bean
        @ConditionalOnMissingBean(HelloService.class)
        public HelloService helloService() {
            HelloService helloService = new HelloService();
            helloService.setMsg(helloServiceProperties.getMsg());
            return helloService;
        }
    }

根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass来判断HelloService这个类在类路径中是否存在,且当这个容器中没有这个Bean的情况下自动配置这个Bean。<p>

5)注册自动配置<p>

在src/main/resources中新建META-INF/spring.factories文件,内容为

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\      com.gnd.springboot.config.HelloServiceAutoConfiguration<br>

其中“\”是为了在换行之后仍能读到属性,若有多个自动配置,以“,”分隔<p>

6)测试自定义自动配置<p>

新建一个maven web工程,添加如下依赖:

    <properties>
        <spring-framework.version>1.4.0.RELEASE</spring-framework.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>spring-boot-starter-hello</groupId>
            <artifactId>com.gnd.springboot</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

spring-boot-starter-hello为之前新建的自定义自动配置starter pom<p>
新建测试启动类

    @RestController
    @SpringBootApplication
    public class Chapter11Application {
        @Autowired
        private HelloService helloService;
        @RequestMapping("/test")
        public String index() {
            return helloService.sayHello();
        }
        public static void main(String[] args){
            SpringApplication.run(Chapter11Application.class, args);
        }
    }

运行测试工程之后,浏览器输入"http://localhost:8080/test"测试,测试结果如下:

<a href="http://p1.bpimg.com/4851/6ff00c546916cb99.png" title="点击显示原始图片"><img src="http://p1.bpimg.com/4851/6ff00c546916cb99t.jpg"></a><p>
新建application.properties配置文件,内容为

    hello.msg=haha

重启工程,浏览器输入"http://localhost:8080/test"测试


关注我的微信公众号:FramePower
我会不定期发布相关技术积累,欢迎对技术有追求、志同道合的朋友加入,一起学习成长!


微信公众号1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,924评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,902评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,716评论 0 239
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,783评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,166评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,510评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,784评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,476评论 0 196
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,196评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,459评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,978评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,321评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,964评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,046评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,803评论 0 193
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,530评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,420评论 2 265

推荐阅读更多精彩内容