Question

I have a settings.xml file in user_directory/.m2 folder.I have set a property in settings.xml. I want it to access it in spring.xml.

setting.xml

<profiles>
    <profile>
    <id>default</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <testName>Test</testName>
    </properties>
    </profile>      
</profiles>

in pom.xml i have written

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

Should I have to create test.properties file inside src/main/resources folder.

name = ${testName}

In spring.xml i have used it as

<context:property-placeholder location="classpath:src/main/resources/test.properties"/>
<bean class="java.lang.String" id="nameTest">
    <constructor-arg value="name"/>
</bean> 

When run.Exception is

Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [src/main/resources/test.properties] cannot be opened because it does not exist

What is going wrong.How can I access properties from settings.xml to spring.xml.

Was it helpful?

Solution

You misconfigured you property place holder. src/main/resource is not in your classpath, you should have put something like:

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

For the configuration of your context, you could :

a. filter your spring context directly:

<bean class="java.lang.String" id="nameTest">
    <constructor-arg value="${testName}"/>
</bean> 

b. Or filter your test.properties configuration file and then inject it as a property-placeholder in your spring.xml:

test.properties:

spring.testName=${testName}

spring.xml:

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

<bean class="java.lang.String" id="nameTest">
    <constructor-arg value="${spring.testName}"/>
</bean> 

OTHER TIPS

Several points I see:

  1. The location property of property-placeholder refers to a file on the class path but you want to use a file on the file system so it would have to be something like this:

    <context:property-placeholder location="file:///user_directory/.m2/settings.properties"/>
    
  2. Your settings file is XML. What is expected by default is actually a file in the Java properties format. There may be ways to use custom XML but I am not familiar with that. So your XML file would translate into something like this:

    profile.id = default
    profile.activation.activateByDefault = true
    profile.properties.testName = Test
    ...
    
  3. When referencing your properties later on in your spring.xml you simply use ${profile.id} to place the ID value from the settings.properties file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top