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: 有的小伙伴获取的配置文件出现了中文乱码问题, 请访问下面博客

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

猜你喜欢

转载自www.cnblogs.com/zhainan-blog/p/11460615.html