Read properties file from WEB-INF folder - java

I want to read properties file from WEB-INF folder and not from the classpath since I dont want to compile my application again if I make any modifications. My file is coming in build in the directory but when I am trying to acces its not showing anything. Please can anyone help me with this. I am using Spring framework. So if there is any method in Spring which will allow us that we are not required to compile our application again and again and the modifications are taken up by the applications on its own.

Add this to your application context configuration file and try.
<bean id="applicationProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>yourPropertiesFile.properties</value>
</list>
</property>
</bean>
To access properties from the properties file, use the bean's ID in your class which must be annotated with #Service or #Component
#Resource(name="applicationProperties")
private Properties anyVariableName;
...
...
String propValue = anyVariableName.getProperty("propertyName");

You can put the properties file in the resources folder. It will not require recompiling of the application.
In spring you can use the following lines to read the property values from property file :
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dash_conf.properties</value>
</list>
</property>
</bean>
Also if you want to read the property file from java class you can use :
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(fileName);
Properties prop = new Properties();
prop.load(in);
Hope this solves your problem.

Related

springMVC : No message found under code 'com.info.write.text' for locale 'en_US'

While reading properties file from folder com.resources I got following error
javax.servlet.jsp.JspTagException: No message found under code 'com.info.write.text' for locale 'en_US'.
I am not using maven. So, I understand that spring will not read the resources automatically.
I know how to write and read data from simple property file in java is simple task as, need to provide path using FileReader now the question is how I can provide path to properties file?
This is some relevant part of my dispatcherServlet-servlet.xml
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message" />
</bean>
here is data of property file i.e (message.property)
com.info.write.text=Greetings of the day
This is how I am trying to use data from property file as message
<p><spring:message code="com.info.write.text" /></p>
and the file structure to message.properties is
src/com/resources/message.properties
How to read properties file in spring without using maven or any build tool(directly) ?
Either use full name in dispatcherServlet-servlet.xml
like
<property name="basename" value="src/com/resources/message" />
or use ClassPath like
<property name="basename" value="classpath*:resources/message" />

Spring resolved property file location needs to resolve those properties

I am using Spring version 4.0.6.RELEASE and am trying to have spring read from a properties file and use one of the resolved properties to provide a location to another properties file. My spring.xml file has the following:
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:application.properties</value>
<value>classpath:version.properties</value>
<!- The below file contains the another file location -->
<value>file:${catalina.base}/conf/instance.properties</value>
<value>${another.file.location}</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
instance.properties contains:
account.id=BlahBlahBlah
another.file.location=file:/Users/beardman/.myapp/local.properties
and /Users/beardman/.myapp/local.properties contains:
magic.number=3
database.endpoint=blah
I keep getting the following warning:
WARN [main] o.s.b.f.c.PropertyPlaceholderConfigurer Could not load properties from ServletContext resource [/${another.file.location}]: Could not open ServletContext resource [/${another.file.location}]
When debugging my code, I can see that the account.id was injected correctly, but I can never get the magic.number or database.endpoint to show up. How can I get spring to use the resolved property from the instance.properties file as the value for the another.file.location?
EDIT: Added property file contents
Spring by default replaces property placeholders with system properties. Since you want to use properties defined in an external file as well, you need to create a PropertyPlaceholderConfigurer
This tag is the shorthand, but you can define PropertyPlaceholderConfigurer as a bean if you need more control. Add this before your applicationProperties bean
<context:property-placeholder location="file:${catalina.base}/conf/instance.properties"/>
Note that properties in the file will override system properties in the default mode. You can specify that system properties are checked first by adding the attribute systemPropertiesMode="override" to the property-placeholder element

Optional additional property file in spring context

I have a default properties file that my app uses but I also need to be able to allow for an additional property file which can be specified by a -D flag on startup and will be pointing to a path on the file system (not in my classpath). What's the correct syntax to do that?
I tried this but it didn't work:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="classpath:/config/config.properties,file:/${additional.configs}" />
</bean>
as it complained that:
java.io.FileNotFoundException: class path resource [config/config.properties,file://var/tmp/cfg/qa.properties] cannot be opened because it does not exist
It looks like the comma delimination isn't working despite me finding some examples suggesting to do it that way. I don't think I can use the list of location beans version of it since the additional attribute file is optional. Any thoughts? I am using spring 3.1.1.
Thanks!
Update: Using the list approach works, however how to make it optional is still outstanding. For now I am using ignoreResourceNotFound=true, however that's not ideal because if someone mistypes the property then it won't fail...
I think you should be able to do this by using a wildcard on the property file you want to be optional. e.g.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/config/config.properties</value>
<value>file:/${additional.configs}*</value>
</list>
</property>
</bean>
Obviously you need to set the additional.configs parameter to something sensible. You can't leave it blank on systems that don't have the file, since the wildcard will then match all files! Instead you can set it to a dummy value for a non-existent file. e.g.
additional.config=/non-existent-file.txt
Spring doesn't throw an error if a wildcard doesn't match anything, so this has the affect of making this property file optional, without having to resort to ignoreResourceNotFound=true.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/config/config.properties</value>
<value>file:/${additional.configs}</value>
</list>
</property>
</bean>
If it still does not work, you can try to specify properties location without slash:
<value>file:${additional.configs}</value>

how to read properties file in spring project?

Before post this Question, I google to get Properties from Spring project(Its NOT web-based project). I am confused as every one are talking about application-context.xml and have configuration like
However, I am working on normal Java Project with Spring(NO Web-app and stuff like that). But I would like to get some common properties from properties file and that needs to be used in JAVA file. How can achieve this by using Spring/Spring Annotations?
Where I should configure myprops.properties file under my project and how to invoke through spring?
My understanding is application-context.xml is used ONLY for web based projects. If not, how should I configure this application-context.xml as I do NOT have web.xml to define the application-context.xml
You can create an XML based application context like:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
if the xml file is located on your class path. Alternatively, you can use a file on the file system:
ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");
More information is available in the Spring reference docs. You should also register a shutdown hook to ensure graceful shutdown:
ctx.registerShutdownHook();
Next, you can use the PropertyPlaceHolderConfigurer to extract the properties from a '.properties' file and inject them into your beans:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:com/foo/jdbc.properties"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
Lastly, if you prefer annotation based config, you can use the #Value annotation to inject properties into you beans:
#Component
public class SomeBean {
#Value("${jdbc.url}")
private String jdbcUrl;
}
As of Spring 4, you can use the #PropertySource annotation in a Spring #Configuration class:
#Configuration
#PropertySource("application.properties")
public class ApplicationConfig {
// more config ...
}
If you would like to have your config outside of your classpath, you can use the file: prefix:
#PropertySource("file:/path/to/application.properties")
Alternatively, you can use an environmental variable to define the file
#PropertySource("file:${APP_PROPERTIES}")
Where APP_PROPERTIES is an environmental variable that has the value of the location of the property file, e.g. /path/to/application.properties.
Please read my blog post Spring #PropertySource for more information about #PropertySource, its usage, how property values can be overridden and how optional property sources can be specified.
You don't have to use Spring.
You can read with plain java like this:
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName));
Can you figure out how your project will be used in the whole app? If your project is used as a build path for a web app and the configuration in your project is achieved through spring annotations, so no doubt you are puzzled about how to add an application.xml file. My suggest is you have to announce the guys who will use your project, tell them what you need and you just need to add #Value("${valuename}") in your code.
Create new property file inside your src/main/resources/ directory and file extension must be .properties e.g. db.properties
Write following context properties in your spring xml configuration file:
<context:property-placeholder location="db.properties"/>
Usage: ${property-key}

Springframework beans

I have not until now had worked with spring framework. I tried reading and reading the spring documentation but could not locate the answer to the following simple question.
The application is ant built to a build directory. So far when I tried to start the JBOSS (or apache) server, the logs says it is unable to build the bean because it could not find
var/config/madagascar.prop.
.
WRT the following snippet in WEB-INF/applicationContext.xml
<bean id="application.home" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System"/>
<property name="targetMethod" value="getProperty"/>
<property name="arguments">
<list>
<value>application.home</value>
</list>
</property>
</bean>
<bean id="propertyFile" class="java.io.File">
<constructor-arg ref="application.home"/>
<constructor-arg value="var/config/madagascar.prop"/>
</bean>
Could you tell me where {application.home} and var/config are expected to be located?
Is it relative to the Eclipse project home or relative to WEB-INF?
What is the bean id="application.home" attempting to do - is it trying to read the value for "application.home" from the system env?
"application.home" is the runtime value of System.getProperty("application.home") and the "propertyFile" bean is a java.io.File object returned from calling new java.io.File(String, String) with the whatever application.home is set to and that second String.
If the bean you wanted was 'propertyFile', the runtime equivalent would be:
File file = new File(System.getProperty("application.home"),"var/config/madagascar.prop");
That config is a very Spring 1.x (read old) way of doing things. XML is a very kludgy way to perform many of these types of initialization, and that's one of the reasons that Spring's #JavaConfig approach became so popular.

Categories