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;
}
}