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

1. 添加pom.xml依賴html

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

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

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

remote.testname=張三
remote.testpass=123456

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

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. 在調用配置文件信息的類中搞事情spring-boot

@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: 有的小夥伴獲取的配置文件出現了中文亂碼問題, 請訪問下面博客測試

https://www.cnblogs.com/zhainan-blog/p/11460488.htmlspa

相關文章
相關標籤/搜索