2013-03-13 34 views
11


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

謝謝!

後來編輯 - 仍在尋找答案: 是否有可能與Spring JavaConfig加載一個屬性文件直接到一個java.util.Properties場?

回答

8

的XML基礎方式:

在Spring配置:

<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") 

用此註釋類將從文件中加載屬性到環境中。然後,您必須將環境自動裝入類以獲取屬性。

@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中。但是您可以創建一個使用此註釋的類作爲包裝器,並以此方式構建屬性。

+0

謝謝,但我感興趣的是如何通過僅使用Spring JavaConfig來獲得此結果,而不使用xml文件... – Roxana 2013-03-13 15:06:19

+0

@Roxana oops。編輯我的帖子。 – jacobhyphenated 2013-03-13 15:40:21

+1

謝謝你的回答。我有一個特殊的情況,我需要一個屬性字段。我會記住你的想法與包裝,但我不知道是否有一個更簡單的解決方案... :) – Roxana 2013-03-13 15:58:16

1

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

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

和Java類只使用

@javax.annotation.Resource 
private Properties myProps; 

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

1

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

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

申報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配置是超級容易如上所示。

+1

感謝百萬。 – vikingsteve 2016-03-03 12:49:25

0

申請。陽明海運

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領域。