簡體   English   中英

java.util.Properties 字段的 Spring JavaConfig

[英]Spring JavaConfig for java.util.Properties field


您能告訴我如何使用 Spring Javaconfig 將屬性文件直接加載/自動裝配到 java.util.Properties 字段嗎?

謝謝!

稍后編輯 - 仍在尋找答案:是否可以使用 Spring JavaConfig 將屬性文件直接加載到 java.util.Properties 字段中?

XML 基礎方式:

在彈簧配置中:

<util:properties id="myProperties" location="classpath:com/foo/my-production.properties"/>

在你的課堂上:

@Autowired
@Qualifier("myProperties")
private Properties myProperties;

僅 JavaConfig

好像有注釋:

@PropertySource("classpath:com/foo/my-production.properties")

使用此注釋類會將文件中的屬性加載到環境中。 然后,您必須將 Environment 自動裝配到類中以獲取屬性。

@Configuration
@PropertySource("classpath:com/foo/my-production.properties")
public class AppConfig {

@Autowired
private Environment env;

public void someMethod() {
    String prop = env.getProperty("my.prop.name");
    ...
}

我沒有看到直接將它們注入 Java.util.properties 的方法。 但是您可以創建一個使用此注釋作為包裝器的類,並以這種方式構建屬性。

聲明一個PropertiesFactoryBean

@Bean
public PropertiesFactoryBean mailProperties() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("mail.properties"));
    return bean;
}

舊代碼具有以下配置

<bean id="mailConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:mail.properties"/>
</bean>

如上所示,將其轉換為 Java 配置非常簡單。

這是一個古老的主題,但也有一個更基本的解決方案。

@Configuration
public class MyConfig {
    @Bean
    public Properties myPropertyBean() {
        Properties properties = new Properties();
        properties.load(...);
        return properties;
    }
}

還有一種直接使用 xml 配置注入屬性的方法。 上下文 xml 有這個

<util:properties id="myProps" location="classpath:META-INF/spring/conf/myProps.properties"/>

而java類只是使用

@javax.annotation.Resource
private Properties myProps;

瞧!! 它加載。 Spring 使用 xml 中的 'id' 屬性綁定到代碼中的變量名稱。

應用程序.yml :

root-something:
    my-properties:
        key1: val1
        key2: val2

您的類型安全 pojo:

import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "root-something")
public class RootSomethingPojo {

    private Properties myProperties;

您的容器配置:

@Configuration
@EnableConfigurationProperties({ RootSomethingPojo .class })
public class MySpringConfiguration {

這會將鍵值對直接注入myProperties字段。

你可以試試這個

@Configuration  
public class PropertyConfig { 

 @Bean("mailProperties")  
 @ConfigurationProperties(prefix = "mail")   
  public Properties getProperties() {
     return new Properties();  
  }

}

確保在 application.properties 中定義屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM