java 读取配置文件的方式

方式一:
//创建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; 使用时直接注入,然后调用属性值
private static String port;
//如果属性是静态的,可以用方法注入
@Value("${server.port}")
public void setPort(Integer port) {
    Student.port= port;
}

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

方式三:

引入依赖

<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;
}调用方式不在描述,依赖注入直接调用
发布了168 篇原创文章 · 获赞 16 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/ajax_yan/article/details/104778701