Spring Boot 读取配置文件的方式
在 Spring Boot 中,读取配置文件的方式有多种,开发者可以选择适合自己项目的方式,以下是其中的几种常用方式:
1. 使用 @Value 读取配置文件
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConfigReader {
@Value("${profile.name}")
private String profileName;
@Value("${profile.desc}")
private String profileDesc;
public void readConfig() {
System.out.println("Profile Name: " + profileName);
System.out.println("Profile Desc: " + profileDesc);
}
}
2. 使用 @ConfigurationProperties 读取配置文件
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "profile")
public class ConfigPropertiesReader {
private String name;
private String desc;
// Getters and Setters
public void readConfig() {
System.out.println("Profile Name: " + name);
System.out.println("Profile Desc: " + desc);
}
}
3. 使用 Environment 读取配置文件
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class EnvironmentConfigReader {
@Autowired
private Environment environment;
public void readConfig() {
String profileName = environment.getProperty("profile.name");
String profileDesc = environment.getProperty("profile.desc");
System.out.println("Profile Name: " + profileName);
System.out.println("Profile Desc: " + profileDesc);
}
}
4. 使用 @PropertySource 读取配置文件
首先,在主类(@SpringBootApplication 注解标记的类)上添加 @PropertySource 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:custom.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后,使用 @Value 注解读取配置文件中的值:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class CustomPropertiesReader {
@Value("${custom.property1}")
private String property1;
@Value("${custom.property2}")
private String property2;
public void readConfig() {
System.out.println("Custom Property 1: " + property1);
System.out.println("Custom Property 2: " + property2);
}
}
5. 使用原生方式读取配置文件
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:custom.properties")
public class CustomPropertiesConfiguration {
// Configuration class to enable @PropertySource
}
然后,在其他类中使用 @Value 注解读取配置文件中的值。