spring boot的一些配置二

1、web项目启动,自动运行指定方法。

定义一个类实现CommandLineRunner接口的run方法
当项目启动后,会自动运行run方法
定义的类上需要加上注解@Component

@Component
public class MyCommandLineRunner implements CommandLineRunner{

    @Override
    public void run(String... var1) throws Exception{
        System.out.println("This will be execute when the project was started!");
    }
}
2、读取配置文件的信息

2种方法。
spring boot 配置文件可以是application.properties和application.yml
相对来说yml的内容格式更加人性化,推荐使用。
假设application.yml内容如下:

spring :
  task :
    pool :
      corePoolSize : 4
      maxPoolSize : 8
      keepAliveSeconds : 60
      queueCapacity : 20
sina:
    account :
        - name : name1
          password: pwd1
        - name : name2
          password: pwd2
        - name : name3
          password: pwd3
        - name : name4
          password: pwd4
project :
    name : demo

第一种:
直接获取单个属性数据

@Value("${project.name}")
private String name;

第二种:
装配进一个对象中
首先定义一个对象:
类上加上注解@ConfigurationProperties(prefix = “spring.task.pool”)
prefix表示自动配置前缀为spring.task.pool的属性值到对象中

@ConfigurationProperties(prefix = "spring.task.pool")
public class TaskThreadPoolConfig {
    private int corePoolSize;

    private int maxPoolSize;

    private int keepAliveSeconds;

    private int queueCapacity;

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getKeepAliveSeconds() {
        return keepAliveSeconds;
    }

    public void setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }

    public int getQueueCapacity() {
        return queueCapacity;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }
}

使用的时候,直接在需要用到的类中注入该类就可以

@Autowired
    private TaskThreadPoolConfig config;

装载集合数据:

@ConfigurationProperties(prefix="sina")
public class Sina {
    private List<Account> account = new ArrayList<>();
    //省略getter和setter方法
}
3、多环境配置

开发,测试和生产环境:
在application.yml同级下新建:

application-dev.properties //开发环境的配置文件
application-test.properties //测试环境的配置文件
application-prod.properties //生产环境的配置文件

在application.yml中增加配置:

spring:
    profiles:
        active: dev
#引用测试的配置文件
        #active: test
#引用生产的配置文件
        #active: prod
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值