Spring讀取Properties配置文件


 一、application.properties 配置文件

  ①:用Spring容器獲取Environment變量,然后getProperty獲取到配置的value

    ConfigurableEnvironment environment = context.getEnvironment(); 
    String name = environment.getProperty("name");

  ②:@Value注解

    使用@Value("${key}"

  ③:@ConfigurationProperties

    @ConfigurationProperties注解有一個prefix屬性,通過指定的前綴,綁定配置文件中的配置,如:

@Component
@ConfigurationProperties(prefix = "global.jdbc")
public class GlobalProperties {
    private String url;
    private String driver;
    private String username;
    private String password;

    ...getter/setter
}

 

 

 

 二、自定義properties 配置文件

  ①:@PropertySource + @Value("${key}") 

    @PropertySource :使用@PropertySource讀取外部配置文件中的k/v保存到運行的環境變量Environment中;

    如:@PropertySource("classpath:mysql.properties")

    取值方式:

      ①:使用@Value("${key}"

      ②:也可以用Spring容器獲取Environment變量,然后getProperty獲取到配置的value

        ConfigurableEnvironment environment = context.getEnvironment(); 
        String name = environment.getProperty("name");

 

  ②:自行直接讀取配置文件的值並緩存

public final class PropertiesUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);

    private PropertiesUtil() {
    }

    private static final Properties PROPERTIES = readProperties(
            "config.properties",
            "mysql.properties",
            "redis.properties",
            "mongo.properties",
            "talos.properties"
    );

    private static Properties readProperties(String... confFile) {
        final Properties properties = new Properties();
        try {
            for (String path : confFile) {
                final ClassPathResource resource = new ClassPathResource(path);
                if (resource.exists()) {
                    properties.load(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
                }
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return properties;
    }

    public static String get(String key) {
        return PROPERTIES.getProperty(key);
    }
}

 

 

END.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM