springboot-配置文件

Pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

这块配置就是Spring Boot父级依赖,有了这个,当前的项目就是Spring Boot项目了,spring-boot-starter-parent是一个特殊的starter,它用来提供相关的Maven默认依赖,使用它之后,常用的包依赖可以省去version标签。

Spring Boot提供了很多”开箱即用“的依赖模块,都是以spring-boot-starter-xx作为命名的。

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

</dependency>

添加devtools后,修改工程内容后可直接访问,不需要手动重启服务,即热部署。

 

application.properties

Spring Boot使用了一个全局的配置文件application.properties,放在src/main/resources目录下或者类路径的/config下。Sping Boot的全局配置文件的作用是对一些默认配置的配置值进行修改。

  1. 系统属性

debug=true

server.port=8081

 

2.自定义属性

share.url=http://www.gary.com/share_url

然后直接在要使用的地方通过注解@Value(value=”${share.url}”)就可以绑定到你想要的属性上面。如:

@Value(value="${share.url}")
private String shareUrl;
@RequestMapping("/share_url")
public String getShareUrl(){
    return shareUrl;
}

3.参数对象

有时候属性太多了,一个个绑定到属性字段上太累,如:

添加配置:

redis.address=127.0.0.1
redis.username=gary
redis.password=123

官方提倡绑定一个对象的bean,这里我们建一个RedisConfigBean.java类,顶部需要使用注解@ConfigurationProperties(prefix = “redis”)来指明使用参数前缀。

package com.gary.configBean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "redis")
public class RedisConfigBean {
    private String address;
    private String username;
    private String password;
}

然后在application中添加EnableConfigurationProperties注解

@SpringBootApplication
@EnableConfigurationProperties({RedisConfigBean.class})
public class NewSpringBootApplication {

 

使用时可直接引用:

@Autowired
private RedisConfigBean redisConfigBean;

@RequestMapping("/redis_properties")
public String getRedisProperties(){
    return redisConfigBean.toString();
}

 

参数间引用

redis.info=${redis.username}-${redis.password}

@Value(value="${redis.info}")
private String redisInfo;
@RequestMapping("/redis_info")
public String getRedisInfo(){
    return redisInfo;
}

3.多环境配置

在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  1. ·application-dev.properties:开发环境
  2. ·application-test.properties:测试环境
  3. ·application-prod.properties:生产环境

至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

如:spring.profiles.active=dev就会加载application-dev.properties配置文件内容

也可以在打完包后,在启动时动态指定配置文件,如:

java -jar .\target\new-spring-boot-1.0-SNAPSHOT.jar --spring.profiles.active=prod

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值