在程序开发中很多时候需要将一些参数放置到配置文件中,以便后期修改使用,比如说数据库链接的参数,本文通过简单的案例来实现Spring Boot读取配置文件的内容

1.首先搭建SpringBoot环境(这里不做过多的介绍),创建的环境如下:

Spring Boot读取配置文件

2.可以看到在resources文件下其实是有一些文件的,这里咱们不去使用,创建一个common.properties文件,写入内容如下:

Spring Boot读取配置文件

内容很简单,就不贴出来了

3.在zj包名下创建CommonConfig.java类,如下:

package com.zj;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * Created by zj on 2018/12/28.
 */
@Configuration
@PropertySource(value = "classpath:common.properties")
@ConfigurationProperties
public class CommonConfig {
    
    @Value("${demo}")
    private String demo;

    @Value("${test}")
    private String test;

    public String getDemo() {
        return demo;
    }

    public void setDemo(String demo) {
        this.demo = demo;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

4.到目前为止就可以直接使用配置文件中对应的内容了,那么咱们来测试一下,在生成框架的测试类中加入测试代码,如下:

package com.zj;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.SimpleDateFormat;
import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ReadConfigurationApplicationTests {

	@Autowired
	private CommonConfig commonConfig;
	@Test
	public void contextLoads() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		System.out.println("运行时间:"+ sdf.format(new Date()));
		System.out.println(commonConfig.getDemo() + " " + commonConfig.getTest());
	}

}

当然也可以不需要在这里调用,大家可以自行通过测试类或者方法来测试,测试结果如下:

Spring Boot读取配置文件

相关文章:

  • 2021-12-03
  • 2021-11-01
  • 2018-09-03
  • 2018-12-27
  • 2021-12-03
  • 2020-07-10
  • 2021-09-19
  • 2021-08-06
猜你喜欢
  • 2020-07-08
  • 2021-08-27
  • 2021-08-08
  • 2020-10-03
  • 2018-04-09
  • 2019-09-26
  • 2019-10-28
  • 2020-10-09
相关资源
相似解决方案