2012-02-13 6 views
94

Sto usando la molla. Ho bisogno di leggere i valori dal file delle proprietà. Questo è il file delle proprietà interne non il file delle proprietà esterne. Il file delle proprietà può essere il seguente.Come leggere i valori dal file delle proprietà?

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

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

Ho bisogno di leggere quei valori dal file delle proprietà non in modo tradizionale. Come raggiungerlo? C'è un ultimo approccio con la primavera 3.0?

+6

Questo non sembra un [Proprietà] (http : //en.wikipedia.org/wiki/.propertie s) file. – Raghuram

+0

Se si tratta di un file di proprietà nel senso di Java - sì. Altrimenti è un formato di file personalizzato che deve essere trattato in modo diverso (e non puoi usare le linee come valori di proprietà in Primavera se non hanno una chiave). –

+2

"Non in modo tradizionale" - cosa intendi con questo? –

risposta

165

Configura PropertyPlaceholder nel vostro contesto:

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

Poi si fa riferimento alle proprietà nei vostri fagioli:

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

EDIT: aggiornato il codice per analizzare proprietà con valori separati da virgola mutliple:

my.property.name=aaa,bbb,ccc 

Se ciò non funziona, è possibile definire un bean con proprietà, iniettare ed elaborare manualmente:

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

e il fagiolo:

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

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

Ciao mrembisz, Grazie per la risposta. Ho già configurato propert-segnaposto per leggere i valori dal file delle proprietà esterne. ma ho un file di proprietà nella cartella delle risorse. ho bisogno di leggere e iniettare. ho bisogno di iniettare tutti i valori nella lista.Grazie! – user1016403

+0

@ user1016403 ha aggiornato la mia risposta – mrembisz

+0

Modificata come suggerito da @Ethan. Grazie per l'aggiornamento, non ho potuto accettare la modifica originale, era già troppo tardi. – mrembisz

32

Nella classe di configurazione

@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

In questo esempio, useresti semplicemente un differente 'app.properties' nel test di produzione v.? In altre parole, una parte del processo di distribuzione dovrebbe sostituire "app.properties" con i valori di produzione? –

+0

@KevinMeredith sì, è possibile, è sufficiente dividere la configurazione di primavera da annotazione profilo http://stackoverflow.com/questions/12691812/can-propertysources-be-chosen-by-spring-profile#answer-14167357 – mokshino

+0

@KevinMeredith che usiamo una cartella esterna al deploy war: come c: \ apps \ sys_name \ conf \ app.properties. Il processo di distribuzione viene semplificato e meno soggetto a errori. – jpfreire

22

Ecco una risposta supplementare che è stato anche di grande aiuto per me capire come lavorato: http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

eventuali fagioli BeanFactoryPostProcessor devono essere dichiarati, con una statica, modificatore

@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

Non è necessario registrare esplicitamente il bean 'PropertySourcesPlaceholderConfigurer' con' @ PropertySource' –

+0

@ dubey-theHarcourtians quale versione di Spring (core) usi? se stai usando Spring Boot non hai nemmeno bisogno di '@ PropertySource' del tutto. –

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

aggiungere alcune spiegazioni – HaveNoDisplayName

+0

utilizzando il contenitore principale non è possibile accedere al file delle proprietà delle risorse, quindi è necessario utilizzare il contenitore j2ee come ApplicationContext ed è necessario utilizzare la convalida a livello di bean come xmlns, xmlns: util, xsi: schemaLocation, xmlns: xsi –

19

ci sono vari modi per raggiungere lo stesso, seguito sono riportati alcuni modi di uso comune a molla

  1. Utilizzo di PropertyPlaceholderConfigurer
  2. Utilizzo di Pro pertySource
  3. Utilizzando ResourceBundleMessageSource
  4. Utilizzando PropertiesFactoryBean

    e molti altri ........................

Supponendo ds.type è la chiave nel file di proprietà.


Utilizzando PropertyPlaceholderConfigurer

Registrati PropertyPlaceholderConfigurer bean-

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

o

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

o

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

dopo la registrazione PropertySourcesPlaceholderConfigurer, ora è possibile accedere a valore

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

Utilizzando PropertySource

Nella versione più recente primavera non c'è bisogno di registrarsi con PropertyPlaceHolderConfigurer@PropertySource, ho trovato un buon link per comprendere la comaptibility della versione-

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

Utilizzando ResourceBundleMessageSource

Registrati Bean-

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

accesso Value-

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

o

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

Utilizzando PropertiesFactoryBean

Registrati Bean-

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

Proprietà Wire esempio in voi Aula

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