java 读取配置文件的方式

百般思念 提交于 2020-03-10 22:16:07
方式一:
//创建Properties对象
Properties prop = new Properties();
//读取classPath中的properties文件
prop.load(ConsumerController.class.getClassLoader().getResourceAsStream("bean.properties"));
//根据键取出值
String className = prop.getProperty("test");//读取bean.properties里面,test的值

 

==================================================================

方式二:

使用工具类,将属性@Value("server.port)类似赋值,类加@Component以服务注入,获取内容时,只需要@Autowired服务工具类,调用属性

@Component
@Data
public class Student {
    @Value("${server.port}")
    private String port;
}
@Autowired
private Student student; 使用时直接注入,然后调用属性值

===================================================================

方式三:

引入依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    <version>2.2.5.RELEASE</version>
    </dependency>
@Component//不加无法注入
@Data//插件lombok帮助省略getset
@EnableConfigurationProperties(Student.class)
@ConfigurationProperties(prefix = "spring.activemq", ignoreUnknownFields = true)//加上注解提示有问题(提示没有经过EnableConfigurationProperties...spring的组件,你懂了,要加上EnableConfigurationProperties这个注解,才能成为spring组件)
public class Student {
    private String brokerUrl;
}调用方式不在描述,依赖注入直接调用
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!