2012-02-13 24 views
94

Yay kullanıyorum. Özellikler dosyasındaki değerleri okumam gerekiyor. Bu, iç özellikler dosyası harici özellikler dosyası değil. Özellikler dosyası aşağıdaki gibi olabilir.Özellikler dosyasından değerler nasıl okunur?

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

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

Bu değerleri, özellik dosyasından geleneksel olarak değil okumalıyım. Nasıl elde edilir? İlkbahar 3.0 ile herhangi bir yeni yaklaşım var mı?

+6

Bu [özelliklerine] gibi görünmüyor (http : //en.wikipedia.org/wiki/.propertie s) dosyası. – Raghuram

+0

Eğer Java anlamda bir özellik dosyası ise - evet. Aksi takdirde, farklı bir şekilde ele alınması gereken özel bir dosya formatıdır (ve eğer bir anahtar yoksa, yayında yalnızca özellik değerleri olarak satırları kullanamazsınız). –

+2

"Geleneksel olarak değil" - Bununla ne demek istiyorsun? –

cevap

165

yapılandır PropertyPlaceholder:

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

Eğer fasulye özellikleri tanımlamaktadır

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

EDIT:

: mutliple virgülle ayrılmış değerler ile mülkiyet ayrıştırmak için kod güncellendi
my.property.name=aaa,bbb,ccc 

Bu işe yaramazsa, özellikleri olan bir fasulye tanımlayabilirsiniz, enjekte ve manuel olarak işlemek:

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

ve fasulye:

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

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

Merhaba mrembisz, Cevabınız için teşekkürler. propert-placeholder'ı harici özellikler dosyasındaki değerleri okumak için zaten yapılandırdım. ama kaynak klasörünün içinde bir özellik dosyası var. Okumalı ve enjekte etmeliyim. Tüm değerleri listeye eklemem gerekiyor.Teşekkürler! – user1016403

+0

@ user1016403 benim yanıt güncellendi – mrembisz

+0

@Ethan tarafından Önerilen tarafından düzenlendi. Güncelleme için teşekkürler, orijinal düzenlemeyi kabul edemedim, çok geç oldu. – mrembisz

32

yapılandırma sınıfında İşte

@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

Bu örnekte, üretim v. Testinde farklı bir 'app.properties 'kullanacak mısınız? Başka bir deyişle, dağıtım sürecinizin bir kısmı "app.properties" değerini üretim değerleri ile değiştirmek olabilir mi? –

+0

@KevinMeredith evet, bahar konfigürasyonunuzu Profil ek açıklamalarına göre bölebilirsiniz http://stackoverflow.com/questions/12691812/can-propertysources-be-chosen-by-spring-profile#answer-14167357 – mokshino

+0

@KevinMeredith savaş dışında bir klasör: c: \ apps \ sys_name \ conf \ app.properties gibi. Dağıtım süreci basitleştirilir ve daha az hataya neden olur. – jpfreire

22

bana nasıl olduğunu anlamak için de çok yardımcı oldu ek bir cevaptır işlendi: http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

.210 herhangi BeanFactoryPostProcessor fasulye değiştirici, bir statik ile beyan edilecek olan

@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

"PropertySourcePlaceholderConfigurer" Bean'i "@ PropertySource" –

+0

@ dubey-theHarcourtians ile Spring (core) sürümünün hangisini kullanıyorsunuz? Spring Boot kullanıyorsanız, tamamen @ PropertySource'a ihtiyacınız yoktur. –

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

bazı açıklama eklemek – HaveNoDisplayName

+0

çekirdek kapsayıcı kullanarak dış kaynak özellikleri dosyasına erişemezsiniz, bu yüzden ApplicationContext gibi j2ee kapsayıcısını kullanmanız gerekir ve xmlns, xmlns, xsi: schemaLocation, xmlns: xsi gibi fasulye düzeyinde doğrulama kullanmanız gerekir –

19

Aşağıda yay

    bazı yaygın kullanılan yollardır, aynı ulaşmak için çeşitli yollar vardır
  1. PropertyPlaceholderConfigurer öğesini kullanma
  2. Pro Kullanma

    PropertiesFactoryBean kullanma ResourceBundleMessageSource

  3. kullanma

  4. ve daha birçok pertySource ........................

ds.type varsayarsak mülk dosyasında anahtarıdır. PropertyPlaceholderConfigurer

Kayıt kullanma


PropertyPlaceholderConfigurer fasulyesi

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

veya

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

veya

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

PropertySourcesPlaceholderConfigurer kaydedilmesi sonra, şimdi value- @PropertySource ile PropertyPlaceHolderConfigurer kayıt son bahar sürümünde PropertySource

gerek kullanma

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

, ben iyi buldum erişebilir link sürümün anlaşılabilirliğini anlamak için

Kayıt fasulyesi

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

Erişim Value-

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

veya

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

PropertiesFactoryBean

Kayıt fasulyesi kullanarak

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

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

Tel Özellikleri örneği size class-içine

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