Java读取配置文件的几种方式

1.手动读

该方式不限配置文件

import java.util.ResourceBundle;

public class MyConfig {

    private static String propertyValue;

    static {
        ResourceBundle bundle = ResourceBundle.getBundle("AAA");
        propertyValue = bundle.getString("property.key");
    }

    public static void staticMethod() {
        // 使用 propertyValue
        System.out.println("Static method: " + propertyValue);
    }

    public void nonStaticMethod() {
        // 使用 propertyValue
        System.out.println("Non-static method: " + propertyValue);
    }
}

2.@Value方式读取,该方式只能为非静态属性初始化赋值

该方式限制配置文件为

application.yml

application.properties

application-{spring.profiles.active}.yml 

application-{spring.profiles.active}.properties

@Component
public class MyConfig {

    private String propertyValue;

    @Value("${property.key}")
    public void setPropertyValue(String value) {
        propertyValue = value;
    }


    public void nonStaticMethod() {
        System.out.println("Non-static method: " + propertyValue);
    }
}

3.Springboot自动配置加载

该方式限制配置文件为

application.yml

application.properties

application-{spring.profiles.active}.yml 

application-{spring.profiles.active}.properties

// B.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "abc")
public class ClassB {
    public static String b;

    // Setters and getters for b (省略getters和setters方法)
}

// A.java
import org.springframework.context.annotation.DependsOn;

@DependsOn("classb") // 指定B类作为A类的依赖
public class ClassA {
    public static String a = B.b;
}

针对静态属性,初始化赋值,需要有依赖关系的加上@DependsOn注解,否则a属性有可能是空值

4.@PropertySource读取指定的配置文件

该方式不限配置文件

package com.example.funda;

import org.springframework.beans.factory.annotation.Value;
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
@PropertySource("classpath:property/funda-${spring.profiles.active}.properties")
@ConfigurationProperties(prefix = "sftp")
@Component
public class FuncA {

    private static String httpHost;

    public static void abc() {
        System.out.println("sftp.http.host: " + httpHost);
    }

    public void setHttpHost(String httpHost) {
        FuncA.httpHost = httpHost;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值