Reputation: 31
A1_M1=X1
A1_M2=X2
A1_M3=X3
A2_M1=X4
Default=X5
Above values are in a property file in test.properties.
I was able to do print the value of X1 for Key A1_M1 as below code.
I need some direction of how can i implement it if my key values are dynamic and i do not know Keys (of property file) until i process another object which is sent a papratmer to the class. I need to process this object to know the Keys, then look into property file if the key exist or not. If exist return the value else return a default value.
**spring-bean.xml**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring--context-
3.0.xsd">
<util:properties id="nodeProperty"location="classpath:config/test.properties" />
<context:property-placeholder properties-ref="nodeProperty" />
<context:component-scan base-package="com.jpmc.selftutor" />
</beans>
Code
SpringDemo.java
package com.jpmc.selftutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
@Component("SpringDemo")
public class SpringDemo {
private static String a1m1;
@Autowired
public SpringDemo(@Value("${A1_M1}") String a1m1){
SpringDemo.a1m1 = a1m1;
}
@SuppressWarnings({ "resource", "unused" })
public static void main(String args[]){
ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext(new String[]
{ "spring-bean.xml" });
System.out.println("Value of a1m1: " +a1m1);
}
}
Upvotes: 3
Views: 2043
Reputation: 96
You can use @Value annotation with default value
@Value("#{nodeProperty['A1_M1'] ?: nodeProperty['Default']}")
Upvotes: 1
Reputation: 10555
Use the below code to get the properties into your object and later you can use getProperty()
method to check if the property value exits. If not return getProperty("Default")
:
@Resource(name = "nodeProperty")
private Properties nodeProperty;
Upvotes: 0