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;
...
}
Related
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.
I would like to use #PropertySource annotation in my Spring project. I do not know what shall be the path for my ceny.properties file. I have the following path,
#PropertySource("classpath:properties\\ceny.properties")
and dictionary structure,
C:\Users\X\IdeaProjects\XDxD\src\main\properties\ceny.properties
I am using IntelliJ. Where shall I put the ceny.properties file. I assume that the classpath is in main.
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'd like to completely externalize my config files so that every *.properties file is in /etc/foo/.
But I don't want everything in one big application.properties so I split certain parts away into individual *.properties files.
How can I tell #PropertySource that it should resolve the location of the given property file exactly as it would do for its application.properties i.e. search for it in every directly (could be multiple) that I specified with "--spring.config.location"?
My class would ideally look this way:
#Configuration
#PropertySource("dpuProfiles.properties")
#ConfigurationProperties("dpu.profiles")
public class DpuProfilesConfiguration {
...
}
It does work if I explicitly specify "file:/etc/foo/dpuProfiles.properties".
I couldn't get "${spring.config.location}/dpuProfiles.properties" or similar substitution with EL working. Makes probably no sense either as the variable could contain multiple directories.
You can do it by specify the the config(s) directory in your -classpath and point it from classpath to your #PropertySource
For your case it will be
CLASSPATH=just_added_as_an_example_jar.jar:/etc/foo/
-classpath "$CLASSPATH"
But you need to change the #PropertySource value as follows
#PropertySource({"classpath:dpuProfiles.properties"})
#ConfigurationProperties({"classpath:dpu.profiles"})
Note - The above example is to run from script.
I'm currently having a problem on saving my default values of a YAML file (which I have defined on my Eclipse). The YAML file does generate, but it is an empty file. (Should be something that I've already typed earlier on the Eclipse). Can somebody figured out what I have missed?
Perhaps there is something wrong in the setup() method on the SettingsManager class, because it is the method that generates the lang.yml file, and the setup() method is called on onEnable() on the Main class.
My full classes on pastebin:
http://pastebin.com/wEeiXyRi (Main.class)
http://pastebin.com/82Hf8nB7 (SettingsManager.class)
I also added the files config.yml and lang.yml in the project folder in my Eclipse.
You need to load the defaults from their config file in your src directory, then using a config stream, set them to your config. For example, with your language config:
defConfigStream = new InputStreamReader(plugin.getResource("lang.yml"), "UTF8");
Then, assuming langConfig is your config variable:
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
langConfig.setDefaults(defConfig);
And save your config.
Bukkit provides a helpful method to save the default config.yml file in the form of JavaPlugin.saveDefaultConfig() (javadocs here) to your plugin's directory. Note that it won't overwrite an existing config file.
If you want to save other files that are contained within your .jar plugin file to the plugin's directory,, you can use the JavaPlugin.saveResource() method (javadocs here). For example, in your onEnable if you include the line this.saveResource("lang.yml", true) the lang.yml in the plugin directory will always be overwritten by the version contained within the jar file.
during enable and disable use
getConfig().options().copyDefaults(true);
reloadConfig();
saveConfig();
the same thing happened to me, the code updates your config before saving, so it doesn't override your changes