I have a spring boot maven java application. I have the application.yml file and the properties specified here are used by a jar dependency of the project and I want to keep this file for them dependencies alone.
There is some additional config I want to use in the application. Is there a way to specify a second configuration file to be used within the project?
Thanks
You can use #PropertySource({"classpath:first.properties", "classpath:second.properties"}) like given below,
#Component
#PropertySource("classpath:config.properties")
public class MySeparateProperties
{
#Value( "${property.path.name}" )
private String prop;
}
Now use this bean to use the properties where ever you want in your application
The only issue is that, if the property path is same for application.yml and config.properties application.yml will have higher priority
Edit 1
If the file is located at resources/config/config.properties then you have to give classpath:config/config.properties
You can specify a different name using the property spring.config.name.
From the docs:
If you do not like application.properties as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property.
Create property file as example x.properties and use #PropertySourse(“classpath:x.propeties”)
When need to use it
Configuration files can be set by spring properties, you can use:
spring.config.name to select the names of the configuration files (separated by comma)
spring.config.location to set the paths where the configuration files are located (separted by comma)
Try to look at springboot reference doc here for details.
Related
I need two application.properties in my Spring Boot App.
I know that using the annotation #PropertySource I can specify more than 1 property files.
I tried to use: #PropertySource({"classpath:application.properties","classpath:external.properties"})
The idea of it is having application.properties with the machine independent properties and this file will be included inside the war file.
The other file (external.properties), will leave in the machine, and won't be included in the war file. Here I want to leave properties like the database connection and so on.
I've already changed catalina.properties for adding the external.properties location into the classpath, but unfortunately when running on Eclipse it doesn't work (complains about the missing database properties.).
If the external properties file will be available in a known location on the machine, then have an environment variable, system property, or command-line argument set up with the path to the file. Then, reference the file in you #PropertySource annotation using file: rather than classpath:
Example: #PropertySource("file:${CONF_DIR}/external.properties")
References:
Spring boot docs on external configuration
PropertySource documentation
Blog post regarding PropertySource
In my project I have seperate application.yml files for each environments, inside each folder for an environment.
NOTE: Below red color yml file made temporarily, to make the code work. But should remove this after fixing. So what I want is to use separate application.yml file according to environment. Specially I need to use local/application.yml for local development
Below has an example of getting env variables in my project
#Component
#Configuration
public class ApplicationProperties {
#Value("${ex.my.url}")
private String myServiceUrl;
// getters setters and nedded stuff
}
But it doesn't work, since could not find a way to mention the needed environment. Because it is in a seperate folder. All the other examples mention the way to get the yml file inside resource folder, without seperate folders.
Any fix for the issue?
in my projects, I specify a profile with the VM option :
-Dspring.profiles.active=local
Then I have a file named application-local.yml
in production :
-Dspring.profiles.active=prod , will use the file application-prod.yml
In the resources folder
Do make file of application.yml, application-local.yml, application-dev.yml etc.. what ever you want
and then in application.yml
spring.profile.active = ${ENV}
now during the run specify the ENV variables from run/debug configuration under Intellij or mention the profile for which you want to build the jar in application.yml.
Alternative, you can use the -D spring.profile.active=dev
at-first, from the documentation:
SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:
A /config subdirectory of the current directory
The current directory
A classpath /config package
The classpath root
So, with passed directory hierarchy you'll get problems.
at-second, for file specification, you could use Profiles. This works as follows:
if no specified profiles - application.properties would be used
for any additional profile also would be used profile with name application-<name>.properties
Thus, if you specify dev and cool profiles, properties application.properties, application-dev.properties, `application-cool.properties, would be in use
UPDATE:
You could pass spring.config.location for property file path specify, but if you want directory hierarchy as you have - you need some customizations using context.initializers.classes and ApplicationContextInitializer
The classic solution is to setup one config file
(I prefer properties because I'm sane)
and allow for an overrides file to be placed on each installed host.
Spring supports this out-of-the-box.
Here is an example:
public static void main(final String[] argumentArray)
{
final StringApplicationBuilder springApplicationBuilder;
springApplicationBuilder = new SpringApplicationBuilder(YourSpringBootApplication.class)
springApplicationBuilder.properties(
"spring.config.location=classpath:/yourConfig.properties,/some/path/to/overrides/directory/yourConfig.properties");
springApplicationBuilder.build().run(argumentArray);
}
I'm really new to Spring and got some questions.
One is.. in my Java class i've got a declaration of an absolute Directory path, where some Images are saved. Now if I want to send my Project to a co-worker or a friend, he needs to change the ImagePath in my Java Code. So I want to use a generalized technique for it, that there is a File where you can just edit the Path and the Project just works like it should.
I have heard of the method where you set up an application.yml and a Configuration Class, but I actually don't know, what to write in these Files.
There are two options for your problem:
One is to use a relative path like src/main/resources and put the images there.
Another option is to set the file path in application.properties file like:
my.images.directory.path=path
And now you can use this property in your classes using #Value:
For Example:
#Value( "${my.images.directory.path}" )
private String imagePath;
Same thing you can also set in a application.yml file.
Also, there are other ways to set the property in the properties file and use it, which you can refer over here.
Hope that helps.
Spring has a number of options when it comes to externalising configuration. In your case, the best option would be to add a property to the application.yml file. Ensure that you add this file to the classpath of your application. Alternatively you can specify the location of this file using spring.config.location command line argument.
Here is a simple application.yml file,
images:
path:/usr/images
You can then create a configuration bean in your application to inject this property.
#Component
public class MyConfig {
#Value("${images.path}")
public String name;
}
Now replace hardcoded path in your application with MyConfig.name.
For a full list of options for externalising configuration, check out this link.
You can use #PropertySource as well. Add a file in /src/main/resources, let's say config.properties containing properties.
config.properties file
images.dir=/path/to/images/dir
In java class, say #Controller add #PropertySource as shown in test code and you will be able to access the property.
You will only be required to update the file
#PropertySource("classpath:config.properties")
#Controller
public class TestController {
#Value("${images.dir}")
private String defaultDb;
...
}
In my spring project I'm having two different conf files which have the same properties.
One of them is in an external directory while the other one is inside the resource of my project.
I want that the external file's properties to override the internal values (if they exist in the external file).
In my configuration class I set the files with the PropertySource annotation:
#PropertySources(
{ #PropertySource("file:${HOME}/conf/application.properties"),
#PropertySource("classpath:/data.properties")
})
By default the PropertySource is working like this:
- Read first property file
- Read second (...) property file - if it contains an already given key, it will be overridden.
Check this here: http://javapapers.com/spring/spring-properties-with-propertysource-annotation/
If you want to use it with XML, check also this answer: What is property resolution order in Spring property placeholder configurer with multiple locations?
Assuming you are working with spring-boot and have fat executable jar,
you can override internal config file properties with external with command line params as follow
java -jar your-executable-fat-jar.jar --spring.config.name=external-prop-file-name --spring.config.location=classpath:/application.properties,file://<external-config-file-parent-dir-path-NOT-EXTERNAL-CONFIG-FILE-PATH>
where
spring.config.name - external config file name
spring.config.location - Locations to look for configuration files
Note: with above config, spring-boot will look for external-prop-file-name.properties in external directory passed in spring.config.location
The order of the declared files is important. If the same key is defined in two or more files, the value associated with the key in the last declared file will override any previous value(s).
From spring docs:
In cases where a given property key exists in more than one .properties file, the last #PropertySource annotation processed will 'win' and override.
So just swap #PropertySource("file:${HOME}/conf/application.properties") with #PropertySource("classpath:/data.properties")
Example:
#PropertySources({#PropertySource("classpath:/data.properties"),#PropertySource("file:${HOME}/conf/application.properties")})
We are using a spring boot application, where properties are loaded from application.yml file instead of application.properties, located at src/main/resources/ which looks like below:
config:
host: localhost:8080
server: 123
And they are being pulled in a .java file like this
#ConfigurationProperties( prefix="config")
public class ConnectionImpl implements Connection{
#Value("${config.host}")
private Stringhost;
}
I am able to retrieve properties this way.
But we are trying to move the config properties from application.yml to a different .yml file which is located at a different location. (src/main/resources/env-config).
Now I am not able to retrieve properties same way, i.e, using #Value annotation. Is there any other annotation I need to add ?
From the documentation:
SpringApplication will load properties from application.properties (or application.yml) 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 class path root
If you don’t like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property. You can also refer to an explicit location using the spring.config.location environment property (comma-separated list of directory locations, or file paths).
The default search path classpath:,classpath:/config,file:,file:config/ is always used, irrespective of the value of spring.config.location. This search path is ordered from lowest to highest precedence (file:config/ wins). If you do specify your own locations, they take precedence over all of the default locations and use the same lowest to highest precedence ordering. In that way you can set up default values for your application in application.properties (or whatever other basename you choose with spring.config.name) and override it at runtime with a different file, keeping the defaults.
You need to supply a command line argument that tells SpringApplication where specifically to look. If everything in resources/ is added to the classpath root, then your command line would look like:
java -jar myproject.jar --Dspring.config.location=classpath:/env-config/service-config.yml
If you have a general application.yml under resources/, the properties in there will still be loaded but will take a lower precedence to the properties file specified on the command line.
Your question doesn't really say what you intend to do, but if you want to have a different configuration for different environments (e.g. development, test, production), there is a simple solution for that.
Place your config files in a file hierarchy like this inside your project:
src/
main/
resources/
application.yml
application-development.yml
application-test.yml
application-production.yml
When you now start your application with
java -jar mySpringApplication.jar -Dspring.profiles.active=development
the configuration from application.yml will be taken as a "base layer", overridden by the configuration in application-development.yml. By this, you can have "default" settings for all environments in application.yml and environment-specific configuration in the application-ENV.yml files. The same works for test and production.
No.
You'll be in a much better position if you avoid hard-coding file path like that within your code base. #ConfigurationProperties used to have a locations attribute but it's deprecated and already removed in 1.5.
In Spring Boot, you configure the Environment which is a single source of truth for your configuration. Rather than having settings buried in code, you should configure Spring Boot to read the files that you want. Read the documentation for spring.config.location. If you want to do this in a more transparent manner, perhaps EnvironmentPostProcessor is what you need