2012-02-13 153 views
94

我正在使用彈簧。我需要從屬性文件讀取值。這是內部屬性文件而不是外部屬性文件。屬性文件可以如下。如何從屬性文件讀取值?

some.properties ---file name. values are below. 

abc = abc 
def = dsd 
ghi = weds 
jil = sdd 

我需要從傳統方式讀取屬性文件中的值。如何實現它? Spring 3.0有最新的方法嗎?

+6

這看起來並不像一個[屬性](HTTP ://en.wikipedia.org/wiki/.propertie s)文件。 – Raghuram 2012-02-13 11:40:37

+0

如果它是Java中的屬性文件 - 是的。否則,它是一種自定義文件格式,需要對待不同的處理方式(如果沒有密鑰,則不能在Spring中將這些行用作屬性值)。 – 2012-02-13 11:50:55

+2

「不以傳統方式」 - 這是什麼意思? – 2012-02-13 11:58:46

回答

165

配置PropertyPlaceholder在上下文:

<context:property-placeholder location="classpath*:my.properties"/> 

然後,你指的是性能在豆類:

@Component 
class MyClass { 
    @Value("${my.property.name}") 
    private String[] myValues; 
} 

編輯:更新的代碼複式逗號分隔值解析屬性:

my.property.name=aaa,bbb,ccc 

如果這不起作用,您可以定義一個bean的屬性,注入和手動處理它:

<bean id="myProperties" 
     class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="locations"> 
    <list> 
     <value>classpath*:my.properties</value> 
    </list> 
    </property> 
</bean> 

和bean:

@Component 
class MyClass { 
    @Resource(name="myProperties") 
    private Properties myProperties; 

    @PostConstruct 
    public void init() { 
    // do whatever you need with properties 
    } 
} 
+0

嗨mrembisz,感謝您的回覆。我已經配置了propert-placeholder以從外部屬性文件中讀取值。但我有一個屬性文件內的資源文件夾。我需要閱讀和注射。我需要將所有值注入列表。謝謝! – user1016403 2012-02-13 12:40:23

+0

@ user1016403更新了我的回答 – mrembisz 2012-02-13 12:56:18

+0

按照@Ethan的建議編輯。感謝您的更新,無法接受原創編輯,已經太晚了。 – mrembisz 2013-03-26 16:15:15

32

在配置類

@Configuration 
@PropertySource("classpath:/com/myco/app.properties") 
public class AppConfig { 
    @Autowired 
    Environment env; 

    @Bean 
    public TestBean testBean() { 
     TestBean testBean = new TestBean(); 
     testBean.setName(env.getProperty("testbean.name")); 
     return testBean; 
    } 
} 
+0

在這個例子中,你是否會簡單地在生產測試中使用不同的'app.properties'?換句話說,部署過程的一部分是用生產值替換'app.properties'嗎? – 2015-07-15 16:54:12

+0

@KevinMeredith是的,你可以,只需通過配置文件註釋拆分彈簧配置http://stackoverflow.com/questions/12691812/can-propertysources-be-chosen-by-spring-profile#answer-14167357 – mokshino 2015-07-27 13:56:38

+0

@KevinMeredith我們使用外部部署戰爭之外的文件夾:如c:\ apps \ sys_name \ conf \ app.properties。部署過程變得簡單並且不易出錯。 – jpfreire 2016-02-12 21:18:18

22

這是一個額外的回答也是有很大的幫助,我聽不懂如何加工:http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

種任何的BeanFactoryPostProcessor豆已經到了靜態聲明,修改

@Configuration 
@PropertySource("classpath:root/test.props") 
public class SampleConfig { 
@Value("${test.prop}") 
private String attr; 
@Bean 
public SampleService sampleService() { 
    return new SampleService(attr); 
} 

@Bean 
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
} 
} 
+0

沒有必要使用@ @ PropertySource來顯式註冊'PropertySourcesPlaceholderConfigurer' Bean – 2017-01-26 21:51:32

+0

@ dubey -Harcourtians您使用哪種Spring(核心)版本?如果你使用Spring Boot,你甚至不需要'@ PropertySource'。 – 2017-01-27 12:05:41

0
[project structure]: http://i.stack.imgur.com/RAGX3.jpg 
------------------------------- 
    package beans; 

     import java.util.Properties; 
     import java.util.Set; 

     public class PropertiesBeans { 

      private Properties properties; 

      public void setProperties(Properties properties) { 
       this.properties = properties; 
      } 

      public void getProperty(){ 
       Set keys = properties.keySet(); 
       for (Object key : keys) { 
        System.out.println(key+" : "+properties.getProperty(key.toString())); 
       } 
      } 

     } 
    ---------------------------- 

     package beans; 

     import org.springframework.context.ApplicationContext; 
     import org.springframework.context.support.ClassPathXmlApplicationContext; 

     public class Test { 

      public static void main(String[] args) { 
       // TODO Auto-generated method stub 
       ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml"); 
       PropertiesBeans p = (PropertiesBeans)ap.getBean("p"); 
       p.getProperty(); 
      } 

     } 
    ---------------------------- 

- driver.properties 

    Driver = com.mysql.jdbc.Driver 
    url = jdbc:mysql://localhost:3306/test 
    username = root 
    password = root 
    ---------------------------- 



    <beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:util="http://www.springframework.org/schema/util" 
       xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> 

      <bean id="p" class="beans.PropertiesBeans"> 
       <property name="properties"> 
        <util:properties location="classpath:resource/driver.properties"/> 
       </property> 
      </bean> 

     </beans> 
+0

添加一些解釋 – HaveNoDisplayName 2016-08-26 07:21:48

+0

使用核心容器您無法訪問外部資源屬性文件,因此您需要使用像ApplicationContext這樣的j2ee容器,並且您需要使用xmlns,xmlns:util,xsi:schemaLocation,xmlns:xsi等bean級別驗證 – 2016-08-26 10:19:13

19

有多種方法來實現相同的,下面是彈簧

    一些常用方法
  1. 使用PropertyPlaceholderConfigurer
  2. 使用Pro pertySource
  3. 使用ResourceBundleMessageSource會
  4. 使用PropertiesFactoryBean

    等等........................

假設ds.type是在你的屬性文件的關鍵。


使用PropertyPlaceholderConfigurer

註冊PropertyPlaceholderConfigurer bean-

<context:property-placeholder location="classpath:path/filename.properties"/> 

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
<property name="locations" value="classpath:path/filename.properties" ></property> 
</bean> 

@Configuration 
public class SampleConfig { 
@Bean 
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
    //set locations as well. 
} 
} 

註冊PropertySourcesPlaceholderConfigurer後,現在您可以訪問值 -

@Value("${ds.type}")private String attr; 

使用PropertySource

在最新版本的春天無需註冊PropertyPlaceHolderConfigurer@PropertySource,我找到了一個好link瞭解版本comaptibility-

@PropertySource("classpath:path/filename.properties") 
@Component 
public class BeanTester { 
    @Autowired Environment environment; 
    public void execute(){ 
     String attr = this.environment.getProperty("ds.type"); 
    } 
} 

使用ResourceBundleMessageSource

註冊Bean-

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
    <property name="basenames"> 
    <list> 
     <value>classpath:path/filename.properties</value> 
    </list> 
    </property> 
</bean> 

訪問價值 -

((ApplicationContext)context).getMessage("ds.type", null, null); 

@Component 
public class BeanTester { 
    @Autowired MessageSource messageSource; 
    public void execute(){ 
     String attr = this.messageSource.getMessage("ds.type", null, null); 
    } 
} 

使用PropertiesFactoryBean

註冊Bean-

<bean id="properties" 
     class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="locations"> 
    <list> 
     <value>classpath:path/filename.properties</value> 
    </list> 
    </property> 
</bean> 

線性能的情況下進入你接收機類

@Component 
public class BeanTester { 
    @Autowired Properties properties; 
    public void execute(){ 
     String attr = properties.getProperty("ds.type"); 
    } 
}