springboot讀取自定義properties配置文件方法


1. 添加pom.xml依賴

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

2. 在resources下建一個config包(當然包名隨意), 在包里建一個remote.properties(老規矩, 文件名隨意)

 3. 在配置文件中寫入測試內容

remote.testname=張三
remote.testpass=123456

4. 寫一個實體類, 屬性和配置文件對應

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Configuration
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource("classpath:config/remote.properties")
@Data
@Component
public class RemoteProperties {
    private String testname;
    private int testpass;
}

5. 在調用配置文件信息的類中搞事情

@EnableConfigurationProperties(RemoteProperties.class)
@RestController
public class PageTestController {

    @Autowired
    RemoteProperties remoteProperties;

    @RequestMapping("testProperties")
    public String testProperties(){
        String str = remoteProperties.getTestname();
        int i = remoteProperties.getTestpass();
        System.out.println(str);
        System.out.println(i);
        return str+i;
    }
}

PS: 有的小伙伴獲取的配置文件出現了中文亂碼問題, 請點擊下方鏈接

解決 springboot 讀取 properties 中文亂碼


免責聲明!

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



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