SpringBoot配置操作

2018-12-08  本文已影响2人  树生1995

配置文件

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

配置项:

自定义属性配置

application.properties内容如下:

my1.age=22
my1.name=battcn

MyProperties1.java内容如下:

@Component
@ConfigurationProperties(prefix = "my1")
public class MyProperties1 {

    private int age;
    private String name;
    // getter setter
}

使用方式:Spring4.x 以后,推荐使用构造函数的形式注入属性

@RequestMapping("/map")
@RestController
public class PropertiesController {
    private static final Logger log = LoggerFactory.getLogger(PropertiesController.class);
    private final MyProperties1 myProperties1;

    @Autowired
    public PropertiesController(MyProperties1 myProperties1) {
        this.myProperties1 = myProperties1;
    }

    @GetMapping("/age")
    public MyProperties1 myProperties1() {          
        log.info(myProperties1.getAge());
        return myProperties1.getAge();
    }
}
自定义文件配置

定义一个名为 my2.properties 的资源文件,内容如下:

my2.age=22
my2.name=Levin

MyProperties2.java 文件内容如下

@Component
@PropertySource("classpath:my2.properties")
@ConfigurationProperties(prefix = "my2")
public class MyProperties2 {

    private int age;
    private String name;
    //  getter setter 
}
多环境化配置(开发、测试、生产)
server.servlet.context-path=/dev
server.port=8081
server.servlet.context-path=/test
server.port=8082
server.servlet.context-path=/prod
server.port=8080

application.properties 配置文件中写入 spring.profiles.active=dev 访问路径为(http://localhost:8081/dev) 对应开发环境。

命令行动态选择运行环境
java -jar xxx.jar --spring.profiles.active=dev
上一篇 下一篇

猜你喜欢

热点阅读