SpringBoot配置

栏目: Java · 发布时间: 5年前

内容简介:除了将配置类注解为Spring自定义配置的IDE提示,需要使用APT技术。因此,需要添加依赖依赖项添加完成后,执行命令
app:
  name: HelloWorld
  version: 1

示例 Java 代码

package bj;

import lombok.Data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, QuartzAutoConfiguration.class})
public class App implements ApplicationListener<ApplicationReadyEvent> {
    public static void main(String[] args) {
        new SpringApplication(App.class) {{
            setWebApplicationType(WebApplicationType.NONE);
        }}.run(args);
    }

    @Resource
    private Settings settings;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.out.println(settings);
    }

    @Component
    @ConfigurationProperties(prefix = "app")
    @Data
    public static class Settings {
        private String name;
        private int version;
    }
}

除了将配置类注解为 Component 外,还可以使用注解 @EnableConfigurationProperties(...) 显示指定启用的配置类。用法:

package bj;

import lombok.Data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;

import javax.annotation.Resource;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, QuartzAutoConfiguration.class})
@EnableConfigurationProperties(App.Settings.class)
public class App implements ApplicationListener<ApplicationReadyEvent> {
    public static void main(String[] args) {
        new SpringApplication(App.class) {{
            setWebApplicationType(WebApplicationType.NONE);
        }}.run(args);
    }

    @Resource
    private Settings settings;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.out.println(settings);
    }

    @ConfigurationProperties(prefix = "app")
    @Data
    public static class Settings {
        private String name;
        private int version;
    }
}

示例控制台输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-12-10 15:44:53.585  INFO 4761 --- [           main] bj.App                                   : Starting App on MacBook-Air-2.local with PID 4761 (/Users/yuchao/temp/java/hellomaven/target/classes started by yuchao in /Users/yuchao/temp/java/hellomaven)
2018-12-10 15:44:53.591  INFO 4761 --- [           main] bj.App                                   : No active profile set, falling back to default profiles: default
2018-12-10 15:44:55.490  WARN 4761 --- [           main] reactor.netty.tcp.TcpResources           : [http] resources will use the default LoopResources: DefaultLoopResources {prefix=reactor-http, daemon=true, selectCount=4, workerCount=4}
2018-12-10 15:44:55.492  WARN 4761 --- [           main] reactor.netty.tcp.TcpResources           : [http] resources will use the default ConnectionProvider: PooledConnectionProvider {name=http, poolFactory=reactor.netty.resources.ConnectionProvider$$Lambda$270/2128961136@6c44052e}
2018-12-10 15:44:55.770  INFO 4761 --- [           main] bj.App                                   : Started App in 3.103 seconds (JVM running for 4.582)
App.Settings(name=HelloWorld, version=1)

启用IDE智能提示

Spring自定义配置的IDE提示,需要使用APT技术。因此,需要添加依赖 spring-boot-configuration-processor

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

依赖项添加完成后,执行命令 mvn clean build ,智能提示即可生效。APT会生成智能提示所需的JSON文件

target/classes/META-INF/spring-configuration-metadata.json

{
  "groups": [
    {
      "name": "app",
      "type": "bj.App$Settings",
      "sourceType": "bj.App$Settings"
    }
  ],
  "properties": [
    {
      "name": "app.name",
      "type": "java.lang.String",
      "sourceType": "bj.App$Settings"
    },
    {
      "name": "app.version",
      "type": "java.lang.Integer",
      "sourceType": "bj.App$Settings",
      "defaultValue": 0
    }
  ],
  "hints": []
}

多级配置示例

有时候只有List和Map数据类型不能满足配置需求,需要嵌套另一个配置类。示例如下:

Yaml配置

logging:
  level:
    root: info

app:
  name: HelloWorld
  version: 1
  author:
    name: Unname
    age: 88

Java代码

package bj;

import lombok.Data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, QuartzAutoConfiguration.class})
public class App implements ApplicationListener<ApplicationReadyEvent> {
    public static void main(String[] args) {
        new SpringApplication(App.class) {{
            setWebApplicationType(WebApplicationType.NONE);
        }}.run(args);
    }

    @Resource
    private Settings settings;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.out.println(settings);
    }

    @ConfigurationProperties(prefix = "app")
    @Component
    @Data
    public static class Settings {
        private String name;
        private int version;
        @Resource
        private Author author;

        @ConfigurationProperties(prefix = "app.author")
        @Component
        @Data
        public static class Author {
            private String name;
            private String age;
        }
    }
}

示例输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-12-10 16:01:41.261  INFO 4798 --- [           main] bj.App                                   : Starting App on MacBook-Air-2.local with PID 4798 (/Users/yuchao/temp/java/hellomaven/target/classes started by yuchao in /Users/yuchao/temp/java/hellomaven)
2018-12-10 16:01:41.267  INFO 4798 --- [           main] bj.App                                   : No active profile set, falling back to default profiles: default
2018-12-10 16:01:43.718  WARN 4798 --- [           main] reactor.netty.tcp.TcpResources           : [http] resources will use the default LoopResources: DefaultLoopResources {prefix=reactor-http, daemon=true, selectCount=4, workerCount=4}
2018-12-10 16:01:43.720  WARN 4798 --- [           main] reactor.netty.tcp.TcpResources           : [http] resources will use the default ConnectionProvider: PooledConnectionProvider {name=http, poolFactory=reactor.netty.resources.ConnectionProvider$$Lambda$269/828088650@6650813a}
2018-12-10 16:01:44.030  INFO 4798 --- [           main] bj.App                                   : Started App in 3.727 seconds (JVM running for 6.006)
App.Settings(name=HelloWorld, version=1, author=App.Settings.Author(name=Unname, age=88))

文章首发: https://baijifeilong.github.io


以上所述就是小编给大家介绍的《SpringBoot配置》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

这就是OKR

这就是OKR

【美】约翰·杜尔(John Doerr) / 曹仰锋、王永贵 / 中信出版社 / 2018-12 / 68.00元

这本书是传奇风险投资人约翰·杜尔的作品,揭示了OKR这一目标设定系统如何促使英特尔、谷歌等科技巨头实现爆炸性增长,以及怎样促进所有组织的蓬勃发展。 20世纪70年代,在英特尔担任工程师时,杜尔首次接触到OKR。之后,作为一个风险投资人,杜尔不遗余力地将这一管理智慧,分享给50多家公司和机构,包括谷歌、亚马逊、领英、脸书、比尔及梅琳达·盖茨基金会,甚至摇滚歌手波诺的公益项目。在杜尔的帮助下,任......一起来看看 《这就是OKR》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器