I want to set my relative file path in a properties file so my SaxReader can pick it up when it runs on Tomcat server. I know this should be easy but I've forgotten forgive me :)
I know Spring Boot has application.properties file but I don't see a way to hook in here.
Is there a way to set the relative path in a properties file that will get picked up by Spring Boot and the SaxReader will see it?
As it is I'm hard coding just the filename and putting the file in the resources folder that serves up the templates and static content such as css and js files. The filePath system.out gives: org.dom4j.DocumentException C:sts-bundle\sts-3.7.2.RELEASE\myFileName the toolsuite root location??? weird!!
Please tell me how to specify the relative path in a properties file.
Thanks!!
You can set the file path like any other string property in Spring Boot properties file and access it from inside the path.
E.g. I have the following set in my application.properties file:
download.directory=temp
and it is used as follows in java class:
#Value("${download.directory}")
private String downloadDirectory;
It is used to download the files, now, if I start the application with jar file present in let's say G:/applications folder then the files will be downloaded into G:/applications/temp.
Related
I have a project with some config files. I need to externalize them to allow the user to edit them. It's a spring boot application and my files are in a yaml format.
It's not application.yaml, it's some custom files with different names.
I use bean annotations. For example, one of my beans looks like this :
#Configuration
#ConfigurationProperties
#PropertySource(value="globalConfiguration.yaml", factory = YamlPropertySourceFactory.class)
public class GlobalConfiguration {
//some fields
//accessors
}
When the file is in src/main/resources, it works well but once built it reads the file inside the jar (which is normal)
What I would like to do is to read in priority the yaml file from a config folder which is near the lib folder like this :
- bin
- config
globalConfiguration.yaml
- lib
myApp.jar
I tried using the parameter --spring.config.location="classpath:./config/" (and /./config and ././config and /config and config...) but nothing work I have this error :
***************************
APPLICATION FAILED TO START
***************************
Description:
Config data location 'classpath:/./config/' does not exist
Action:
Check that the value 'classpath:./config/' is correct, or prefix it with 'optional:'
EDIT :
Now I tried to add my config files to the classpath like this :
set CLASSPATH=%APP_HOME%\config\*;%APP_HOME%\lib\myJar.jar;someDepencies.jar
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %MYAPP_OPTS% -classpath "%CLASSPATH%" my.Main.Class %*
It's the bat generated by gradle when I build the project so I just added %APP_HOME%\config\*; to the classpath variable.
But it didn't change anything.
Finally it had nothing to do with the classpath. the spring.config.location works perfectly well but the directory used is the current one when launching the bat and my app was on a windows shared folder so I wasn't able to do a cd \mysharedfolder.. .
To make it works, there was two option :
To move the app in a local folder. Then move to the folder of the app and so the relative path works from there.
The second option is to set the complete path of the config folder like this :
--spring.config.location="\\\\mysharedfolder\\someSubDirectories\\config\\"
In spring boot application how do I give an external windows path using #Value Spring annotation and Resource
The below example works fine that look into resources folder but I want to give the path outside of application like c:\data\sample2.csv
#Value("classPath:/sample2.csv")
private Resource inputResource;
...
#Bean
public FlatFileItemReader<Employee> reader() {
FlatFileItemReader<Employee> itemReader = new FlatFileItemReader<Employee>();
itemReader.setLineMapper(lineMapper());
itemReader.setLinesToSkip(1);
itemReader.setResource(inputResource);
and if I want to get the value from properties file in annotaion, whats the format to put the path in windows?
i tried these, none of them worked:
in code
#Value("${inputfile}")
in properties file:
inputfile="C:\Users\termine\dev\sample2.csv"
inputfile="\\C:\\Users\\termine\\dev\\sample2.csv"
inputfile="C:/Users/termine/dev/sample2.csv"
inputfile="file:\\C:\Users\termine\dev\sample2.csv"
inputfile="file://C://Users//termine///dev//sample2.csv"
When you use classpath spring will try to search with the classpath even if you provide the outside file path.
so instead of using classpath: you can use file:
Ex.
#Value("file:/sample2.csv") //provide full file path if any
Use the key spring.config.location in properties to set the config location. Spring-boot will by default load properties from the locations, with precedence like below :
A /config subdir of the current directory.
The current directory
A classpath /config package
The classpath root
and apart from this when you start the jar or in application.properties you can provide the location of the config file like :
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
You can serve static files from the local disk, by making the resource(s) "sample2.csv" as a static resource. An easy way to do this is by adding spring.resources.static-locations configuration to your applicaiton.properties file. Example:
spring.resources.static-locations=file:///C:/Temp/whatever/path/sample2.csv",classpath:/static-files, classpath:/more-static-resource
When I did this in one of the projects, I was able to access the file form the browser using localhost:8080/sample2.csv.
My Spring Boot project contains an XML file within the src/main/resources folder, which is the common location for such a file.
Running locally and also on Pivotal CloudFoundary, I am able to locate the file and read it in, but on Beanstalk the process results in an empty file.
Code to locate and read file:
URL url = getClass().getResource("/myFile.xml");
LOG.info("File location: " + url.toString());
Resulting log entry:
File location: jar:file:/var/app/current/application.jar!/WEB-INF/classes!/myFile.xml
When I SSH into EC2 instance, I can find the jar in the specified directory.
Do I need to configure Maven to move this file somewhere?
UPDATE
I've since realized that I need to treat this file as in InputStream as it's packaged within the jar.
I'm now using the following code which results in the follow errors:
FileUtils.copyInputStreamToFile(new ClassPathResource("myFile.xml").getInputStream(), myFile);
java.lang.NullPointerException: null
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:345) ~[commons-io-2.5.jar:2.5]
and
FileUtils.copyInputStreamToFile(new ClassPathResource("classpath:myFile.xml").getInputStream(), myFile);
java.io.FileNotFoundException: class path resource [classpath:myFile.xml] cannot be opened because it does not exist
Thanks!
How does your pom.xml look like? Maybe there is a resource-filter active?
In a spring application you could use File file = ResourceUtils.getFile("classpath:myFile.xml"); to read a resource file.
Could you check the result by using ResourceUtils?
Here the link to the api-documentation:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ResourceUtils.html#getFile-java.lang.String-
I can't find an answer to this question on stackoverflow hence im asking here so I could get some ideas.
I have a Spring Boot application that I have deployed as a war package on Tomcat 8. I followed this guide Create a deployable war file which seems to work just fine.
However the issue I am currently having is being able to externalize the configuration so I can manage the configuration as puppet templates.
In the project what I have is,
src/main/resources
-- config/application.yml
-- config/application.dev.yml
-- config/application.prod.yml
-- logback-spring.yml
So how can I possibly load config/application.dev.yml and config/application.prod.yml externally and still keep config/application.yml ? (contains default properties including spring.application.name)
I have read that the configuration is load in this order,
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
Hence I tried to load the configuration files from /opt/apache-tomcat/lib to no avail.
What worked so far
Loading via export CATALINA_OPTS="-Dspring.config.location=/opt/apache-tomcat/lib/application.dev.yml"
however what I would like to know is,
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
And is there a better method to achieve this ?
You are correct about load order. According to Spring boot documentation
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
[Note]
You can also use YAML ('.yml') files as an alternative to '.properties'.
This means that if you place your application.yml file to /opt/apache-tomcat/lib or /opt/apache-tomcat/lib/config it will get loaded.
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
However, if you place application.dev.yml to that path, it will not be loaded because application.dev.yml is not filename Spring is looking for. If you want Spring to read that file as well, you need to give it as option
--spring.config.name=application.dev or -Dspring.config.name=application.dev.
But I do not suggest this method.
And is there a better method to achieve this ?
Yes. Use Spring profile-specific properties. You can rename your files from application.dev.yml to application-dev.yml, and give -Dspring.profiles.active=dev option. Spring will read both application-dev.yml and application.yml files, and profile specific configuration will overwrite default configuration.
I would suggest adding -Dspring.profiles.active=dev (or prod) to CATALINA_OPTS on each corresponding server/tomcat instance.
I have finally simplified solution for reading custom properties from external location i.e outside of the spring boot project. Please refer to below steps.
Note: This Solution created and executed windows.Few commands and folders naming convention may vary if you are deploying application on other operating system like Linux..etc.
1. Create a folder in suitable drive.
eg: D:/boot-ext-config
2. Create a .properties file in above created folder with relevant property key/values and name it as you wish.I created dev.properties for testing purpose.
eg :D:/boot-ext-config/dev.properties
sample values:
dev.hostname=www.example.com
3. Create a java class in your application as below
------------------------------------------------------
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
#PropertySource("classpath:dev.properties")
#ConfigurationProperties("dev")
public class ConfigProperties {
private String hostname;
//setters and getters
}
--------------------------------------------
4. Add #EnableConfigurationProperties(ConfigProperties.class) to SpringBootApplication as below
--------------------------------------------
#SpringBootApplication
#EnableConfigurationProperties(ConfigProperties.class)
public class RestClientApplication {
public static void main(String[] args) {
SpringApplication.run(RestClientApplication.class, args);
}
}
---------------------------------------------------------
5. In Controller classes we can inject the instance using #Autowired and fetch properties
#Autowired
private ConfigProperties configProperties;
and access properties using getter method
System.out.println("**********hostName******+configProperties.getHostName());
Build your spring boot maven project and run the below command to start application.
-> set SPRING_CONFIG_LOCATION=<path to your properties file>
->java -jar app-name.jar
So i can access properties file if its in WEB-INF/classes.
However if I keep the same file under TOMCAT/conf and updating catalina.properties to point to the path, I get an error like Name not bound.
I have almost tried everything...even tried with absolute path
if your file.properties file is in the WEB-INF/classes folder? Then:?
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/file.properties");
Only way I could solve it was
1. Create a env folder under tomcat_home and put the config.properties there
2. update catalina.properties and add the tomcat_home\env path in common loader
3. Comment out from spring security XML
Once I commented the above line It ran fine.