首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 讀取設定檔 (properties/yaml) 完整指南:XML、注解、Environment 多種方式

     編輯:Java 相關知識

前言

Spring 專案中讀取外部設定檔是基礎技能。本文系統整理四種主流方式:PropertiesFactoryBean (XML)、@PropertySource + Environment (注解)、@ConfigurationProperties (型別安全綁定)、Resource 直接讀取,並說明適用場景與優缺點比較。

方式一:XML 宣告 PropertiesFactoryBean (傳統專案常見)

applicationContext.xml

<bean id="configProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:jdbc.properties"/>
    <!-- 多檔案合併
    <property name="locations">
        <list>
            <value>classpath:jdbc.properties</value>
            <value>classpath:redis.properties</value>
        </list>
    </property> -->
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="fileEncoding" value="UTF-8"/>
</bean>

Java 程式碼取得

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Properties props = (Properties) ctx.getBean("configProperties");
String driver = props.getProperty("jdbc.driverClassName");

方式二:@PropertySource + Environment (Spring 3.1+ 推薦)

配置類

@Configuration
@PropertySource(value = "classpath:jdbc.properties", encoding = "UTF-8")
public class AppConfig {
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        ds.setJdbcUrl(env.getProperty("jdbc.url"));
        ds.setUsername(env.getProperty("jdbc.username"));
        ds.setPassword(env.getProperty("jdbc.password"));
        return ds;
    }
}

多環境切換

@PropertySource(value = {
    "classpath:application-${spring.profiles.active}.properties",
    "classpath:application.properties" // 共用預設值
}, encoding = "UTF-8", ignoreResourceNotFound = true)

方式三:@ConfigurationProperties (Spring Boot 風格,型別安全)

jdbc.properties

jdbc.driver-class-name=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=root
jdbc.password=secret
jdbc.pool.max-size=20

綁定類

@Configuration
@ConfigurationProperties(prefix = "jdbc")
@PropertySource("classpath:jdbc.properties")
public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private Pool pool = new Pool();

    // Getter/Setter...
    public static class Pool {
        private int maxSize;
        // Getter/Setter...
    }
}

啟用

@EnableConfigurationProperties(JdbcProperties.class)
@SpringBootApplication
public class Application { ... }

注入使用:
@Autowired JdbcProperties jdbcProps;

方式四:直接使用 Resource 讀取原始檔案內容

程式碼式讀取

Resource resource = new ClassPathResource("config/test.txt");
try (InputStream is = resource.getInputStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
    String content = br.lines().collect(Collectors.joining("\n"));
    System.out.println(content);
}

注入 Resource (XML)

<bean id="resourceBean" class="com.example.ResourceBean">
    <property name="resource" value="classpath:/config/test.txt"/>
</bean>

public class ResourceBean {
    private Resource resource;
    // Getter/Setter
    public void printContent() throws IOException {
        try (InputStream is = resource.getInputStream()) {
            System.out.println(new String(is.readAllBytes(), StandardCharsets.UTF_8));
        }
    }
}

方式比較總結

方式優點缺點適用場景
PropertiesFactoryBean純 XML、無侵入、支援合併多檔需手動轉型、無型別安全、重構困難舊專案維護、純 XML 配置
@PropertySource + Environment型別安全(getProperty)、支援 SpEL、多環境屬性分散、無巢狀結構支援中小專案、快速原型
@ConfigurationProperties強型別、IDE 提示、驗證(JSR-303)、巢狀物件需 Spring Boot 或額外啟用、類別膨脹Spring Boot 專案、大型專案
Resource 直接讀取完全控制、非 Properties 格式(JSON/YAML/純文字)手動解析、無熱重載、無型別轉換讀取模板、腳本、證書、任意二進位

YAML 設定檔支援 (SnakeYAML)

Spring Boot 內建支援 application.yml;傳統 Spring 需自行添加 YamlPropertySourceFactory:

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        return new PropertiesPropertySource(name, factory.getObject());
    }
}

@PropertySource(value = "classpath:config.yml", factory = YamlPropertySourceFactory.class)
@Configuration
public class YamlConfig { ... }

熱重載與最佳實踐

  • Spring Boot DevTools:開發期自動重啟,application.properties 修改即時生效。
  • Spring Cloud Config / Nacos / Apollo:生產環境集中管理、動態推送、版本控制、灰度發布。
  • 加密敏感值:spring-cloud-config-server 支援 {cipher} 前綴,或使用 jasypt-spring-boot。
  • 統一編碼 UTF-8:所有 @PropertySource、PropertiesFactoryBean 明確指定 encoding="UTF-8"。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved