IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Java Discussion :

Manipuler plusieurs .properties


Sujet :

Spring Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Avril 2011
    Messages
    17
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2011
    Messages : 17
    Par défaut Manipuler plusieurs .properties
    Bonjour,

    Etant encore peu habitué avec spring, j'ai quelque soucis avec la manipulation de plusieurs fichiers .properties

    J'explique plus en détail le problème :

    Le chemin d'accès à un fichier de configuration se trouve dans un autre fichier de configuration (pour être facilement modifié)


    config.properties:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    file.properties.name=test/Voiture1.properties
    Voiture1.properties:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    voiture.marque=mercedes
    voiture.vitesseMax=150
    voiture.couleur=bleu

    Et là les choses deviennent compliqué, dans mon fichier applicationContext.xml je ne sait pas comment recupérer la valeur de file.properties.name directement :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <bean name="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    		<property name="locations">
    			<list>
    				<bean class="org.springframework.core.io.ClassPathResource">
    					<constructor-arg>
    						<value>test/config.properties</value>
    					</constructor-arg>
    				</bean>
    				<bean class="org.springframework.core.io.ClassPathResource">
    					<constructor-arg>
    						<!-- <value>test/Voiture1.properties</value> -->
    						<value>${file.properties.name}</value>
    					</constructor-arg>
    				</bean>
    			</list>
    		</property>
    	</bean>
    Quand je met directement le chemin du fichier, tout se passe bien, c'est bien '${file.properties.name}' qui n'est pas compris.

    voilà l'erreur :
    26 avr. 2011 14:48:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@758fc9: startup date [Tue Apr 26 14:48:20 CEST 2011]; root of context hierarchy
    26 avr. 2011 14:48:21 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [test/applicationContext.xml]
    26 avr. 2011 14:48:21 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
    INFO: Loading properties file from class path resource [test/config.properties]
    26 avr. 2011 14:48:21 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
    INFO: Loading properties file from class path resource [${file.properties.name}]
    26 avr. 2011 14:48:21 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
    INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14c1103: defining beans [propertyPlaceholder,Voiture1,Voiture2,Garage]; root of factory hierarchy
    org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [${file.properties.name}] cannot be opened because it does not exist
    Exception in thread "main" java.lang.NullPointerException
    at test.test.main(test.java:23)
    et je vous garantis que mes fichier sont au bon endroit !

    TestS2
    ....|
    .....----src
    ...........|
    ...........-----test
    ....................|
    ....................|-----applicationContext.xml
    ....................|-----config.properties
    ....................------Voiture1.properties


    Merci d'avance pour votre aide !

  2. #2
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    les deux bean "<bean class="org.springframework.core.io.ClassPathResource">" sont interprété avant le propertyplaceholder, file.name n'est donc pas encore existant à ce moment là. Si vous voulez utiliser une property d'un fichier pour initialiser un autre propertyplaceholder, il faut créer deux beans séparés propertyplaceholder, en oubliant pas de mettre un depends-on dans le deuxième pour garantir l'ordre de chargement

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    <bean name="propertyPlaceholder" id="propertyMain"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location">test/config.properties</property>
    </bean>
    <bean name="propertyPlaceholder" id="propertySecond" 
        depends-on="propertyMain"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location">${file.properties.name}</property>
    </bean>

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Avril 2011
    Messages
    17
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2011
    Messages : 17
    Par défaut
    Merci beaucoup pour ta réponse, je ne connaissait pas encore le système du 'depends-on'

    Les problèmes ne venant jamais seul, maintenant je crois que le problème est la façon d'indiquer dans quel fichier de configuration aller rechercher

    Explication :
    j'ai un bean tout simple (Voiture) et j'essaye de lui faire recherche la valeur du champ 'voiture.marque' dans Voiture1.properties

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <bean name="propertyPlaceholder" id="config" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    		<!-- <property name="ignoreResourceNotFound" value="true" />
    		<property name="ignoreUnresolvablePlaceholders" value="true"/> -->
    		<property name="locations">
    			<value>test/config.properties</value>
    		</property>
    	</bean>
     
    	<bean name="propertyPlaceholder2" depends-on="config" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    		<property name="locations">
    		<value>${file.properties.name}</value>
    		</property>
    	</bean>
     
     
     
    	<bean id="Voiture1" class="test.Voiture">
    	<property name="marque">
    		<value>${voiture.marque}</value>
    	</property>
    	</bean>
    J'obtiens pour l'instant l'erreur suivante :
    Exception in thread "main" java.lang.NullPointerException
    at test.test.main(test.java:23)
    org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'Voiture1' defined in class path resource [test/applicationContext.xml]: Could not resolve placeholder 'voiture.marque'
    Merci de l'aide.

    Je vous tiens au courant si je progresse

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Avril 2011
    Messages
    17
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2011
    Messages : 17
    Par défaut
    désolé pour le double-post, mais impossible d'avancer...

    Je fais un récapitulatif :
    Pour bien commencer, voici mon fichier test.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    package test;
     
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
     
    public class test
    {
     
     
    	public static void main(String[] arg)
    	{
    		ApplicationContext context = null;
     
    		try
    		{
    			context = new ClassPathXmlApplicationContext("test/applicationContext.xml");
    		}
    		catch (Exception e){
    			e.printStackTrace();
    		}
    		BeanFactory factory=context;
     
    	    Voiture myBean=(Voiture)factory.getBean("tutur");
    		myBean.afficher();
    	}
    }
    Dans applicationContext.xml, je définis 3 beans importants :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     
     
     
     
    	<bean name="tata" id="propertyMain" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	        <property name="locations">
    	        	<value>test/config.properties</value>
    	        </property>
    	</bean>
     
    	<bean name="toto"  id="propertySecond" depends-on="propertyMain" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	        <property name="locations">
    	        	<value>${file.properties.name}</value>
    	        </property>
    	</bean>
     
     
    	<bean id="tutur" depends-on="propertySecond" class="test.Voiture">
    		<property name="marque">
    			<value>${voiture.marque}</value>
    		</property>
    	</bean>
     
    </beans>

    Voici mes deux fichiers properties :

    config.properties :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    file.properties.name=exemple/Voiture1.properties
    Voiture1.properties :

    Et pour ceux qui ont un doute sur ma classe voiture :
    Voiture.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package test;
     
    public class Voiture {
    	private String marque;
     
    	public void afficher(){
    		System.out.println("marque : "+this.marque);
    	}
     
    	public void setMarque(String marque) {
    		this.marque = marque;
    	}
     
    	public String getMarque() {
    		return marque;
    	}
    }

    Voilà, même après avoir grandement simplifié mon code, j'ai toujours l'erreur suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    27 avr. 2011 09:50:32 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@758fc9: startup date [Wed Apr 27 09:50:32 CEST 2011]; root of context hierarchy
    27 avr. 2011 09:50:32 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [test/applicationContext.xml]
    27 avr. 2011 09:50:32 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
    INFO: Loading properties file from class path resource [test/config.properties]
    27 avr. 2011 09:50:32 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
    INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d08633: defining beans [propertyMain,propertySecond,tutur]; root of factory hierarchy
    org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'tutur' defined in class path resource [test/applicationContext.xml]: Could not resolve placeholder 'voiture.marque'
    	at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)
    	at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:220)
    	at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:84)
    	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:668)
    	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:643)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:437)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    	at test.test.main(test.java:17)
    Exception in thread "main" java.lang.NullPointerException
    	at test.test.main(test.java:25)
    j'ai mis en rouge ce qui me semble être le plus inquiétant dans le message d'erreur.


    Mon arborescence se présente comme ceci : (elle a légèrement été modifié depuis hier.)
    TestS2
    ......|--src
    .............|--exemple
    .............|..........|----Voiture1.properties
    .............|--test
    .....................|--Voiture.java
    .....................|--test.java
    .....................|--applicationContext.xml
    .....................|--config.properties


    EDIT :

    J'ai un peu avancé, j'ai trouvé cette note sur le forum officiel :
    If you want two different PropertyPlaceholderConfigurers to resolve the same placeholder syntax - by default: ${...} - then you need to set each PropertyPlaceholderConfigurer's "ignoreUnresolvablePlaceholders" flag to "true". Else, each placeholder configurer will complain if it finds a placeholder that it cannot resolve (as it doesn't know about the other configurer and assumes that an unresolvable placeholder constitutes a fatal error).

    Alternatively, you could also use different placeholder syntax: PropertyPlaceholderConfigurer's "placeholderPrefix" and "placeholderSuffix" settings allow for specifying specific prefix/suffix syntax for each configurer. For example, one configurer could keep resolving ${...} while another one could resolve #{...}
    Je pense la solution du 'ignoreUnresolvablePlaceholders' incomplète car elle ne fonctionne pas par chez moi...
    J'opte dont plutôt pour la solution qui consiste à préfixer les PropertyPlaceholderConfigurer, seulement je n'arrive pas à le mettre en place, j’obtiens une erreur qui dit qu'il ne trouve pas 'file.properties.name' (qui est dans mon premier PropertyPlaceholderConfigurer).

    Au passage je n'utilise pas maven, car j'ai lu quelque part : (ça pourra servir à d'autres)
    Actually, maven seems to replace properties that end with "properties", like "${test.properties}". It happens with maven 2.0.7 in projects without any plugins (so apparently is default maven behavior).
    A workaround is to rename the placeholder, for example "${test.props}".

    Qui eut cru que spring était si capricieux ?

    Merci d'avance à toute personne qui tentera de m'aider

Discussions similaires

  1. Réponses: 3
    Dernier message: 29/12/2008, 15h22
  2. ActionScript 2 Manipuler plusieurs clips créés avec une boucle for
    Par adinx dans le forum ActionScript 1 & ActionScript 2
    Réponses: 7
    Dernier message: 09/04/2008, 15h01
  3. [HF] Manipuler plusieurs fichiers liés
    Par lemerite dans le forum WinDev
    Réponses: 5
    Dernier message: 21/11/2007, 15h26
  4. Comment manipuler plusieurs fichiers Excel
    Par Olivier0 dans le forum Macros et VBA Excel
    Réponses: 16
    Dernier message: 16/08/2007, 08h38
  5. [vba - excel] manipuler plusieurs fichers excels à la suite
    Par ash_rmy dans le forum Macros et VBA Excel
    Réponses: 1
    Dernier message: 06/09/2006, 16h11

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo