利用IDEA構建springboot應用-配置文件


application.properties配置文件(不建議采用這種配置)

配置文件采用:application.yml文件會更簡便,要帶空格

屬性配置與類中取值

添加bean屬性配置到一個類里面,采用Get/Set方法來調用

 

 屬性注解

application.properties

自定義屬性與加載

我們在使用Spring Boot的時候,通常也需要定義一些自己使用的屬性,我們可以如下方式直接定義:

 

然后通過@Value("${屬性名}")注解來加載對應的配置屬性,具體如下:

@Value

 

package com.tanlei.demo1.entity;

import org.springframework.beans.factory.annotation.Value;

/**
 * @author:Mr.Tan
 * @Create:2018-10-18-13-19
 **/
public class ProDemo {
    @Value("${com.didispace.blog.name}")
    private String name;
    @Value("${com.didispace.blog.title}")
    private String title;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

 按照慣例,通過單元測試來驗證ProDemo中的屬性是否已經根據配置文件加載了 

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
	@Autowired
	private BlogProperties blogProperties;
	@Test
	public void getHello() throws Exception {
		Assert.assertEquals(blogProperties.getName(), "程序猿DD");
		Assert.assertEquals(blogProperties.getTitle(), "Spring Boot教程");
	}
}

  

@Component

@ConfigurationProperties

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM