i've been working with Spring for some time and have a question regarding the very common configuration properties files (like the common application.properties that comes with every spring boot app you initialize). Recently, i also found that configurations like this can be done in yaml files. I have two questions:
When in a application.properties file, we write something like:
# application.properties
spring.debug = true
some-random-value = 15
does this mean that these values will be injected in the application context?
When we write something like:
# application.properties
spring.debug = true
does this mean, that somewhere, there is some class, that has an attribute that looks something like this? -->
#Component
class SomeClass{
#Value("spring.debug")
boolean shouldIRunInDebugMode;
...
}
2.a. If the answer to question 2 is yes, then how can I, looking at something like this:
# application.properties
spring.debug = true
find that class that is expecting that value. The same would apply to if i was looking at something like:
# application.yaml
someThidPartyLibraryName:
shouldWeLog: true
If i see a yaml configuration file, just looking at all the configuration there usually is not enough for me to know what is happening. How can i find the class that is being affected by this configuration, so that i can better understand what this config is doing?
Thank you!
The response is generally yes. If you declare a property in the application.properties or application.yaml is mainly, because you would use it later in the code, for example injecting in some bean with the support of #Value annotation. However, there are also many built-in properties (let's say for example server.port), which you usually don't have to declare and therefore you won't see explicitly in the code. Use an IDE to search the configuration properties and the manual to check the preconfigured ones in case of need.
Your understanding regarding spring value injections from application.properties is correct. #2 - is Yes. Any property from application.properties can be injected to any java class as #Value.
Regarding #2.a - Yaml is just another format on how you organize your variable hierarchy by indentations. That's a superset to the JSON structure.
For example,
in application.properties file you can add something like this
myapp.db.url=<dburl>
myapp.db.username=<dbuser>
myapp.db.password=<dbpassword>
the same can be represented in Yaml in a much efficient manner as below
myapp:
db:
url:<dburl>
username:<dbuser>
password:<dbpassword>
And in either case, for your Jave file you can inject as
#Value("myapp.db.url"
private String dbUrl;
Properties defined in yaml or a properties file may be accessed using the #Value annotation to inject, or using a #ConfigurationProperties class - see https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-typesafe-configuration-properties for complete details.
Finding the property usage is supported by some IDEs - IntelliJ allows you to click through. Otherwise it's a search through the source. For #ConfigurationProperties, once you find the class then just look for code that calls its accessor methods.
Properties files and yaml files are used in Spring Boot for configurations. The main difference between the two is yaml provides structuring/grouping of configurations where as Properties are usually flat and may be repeating the same information:
For example;
Properties file
server.port = 8080
server.host = localhost
yaml file
server:
port: 8080
host: localhost
But in a Spring Boot AutoConfiguration class regardless of yaml or Properties used, a following looking ConfigurationProperties class will be used which will map server.port and server.host
#ConfigurationProperties(prefix = "server")
public class ServerConfiguration {
private int port;
private String host;
}
#Configuration
#EnableConfigurationProperties(ServerConfiguration.class)
public class ServerAutoConfiguration {
}
Hope this answers your questions.
Related
I'm trying to configure a simple thymeleaf text template in my spring boot configuration and got to the point where the thymeleaf variable placeholder and the spring boot configuration property placeholder interfer (afaik both use the SpEL) when the template contains a colon (e.g. "[(${#dates.format(date, 'dd-MM-yyyy HH:mm')})]" as spring boot tries to resolve the variable "#dates.format(date, 'dd-MM-yyyy HH" but uses default value "mm')" instead.
I tried to change the spring boot prefix of the PropertySourcesPlaceholderConfigurer, but then some of my included libraries no longer work as they use the ${} variables
Is there a way to extend thymeleaf to treat %{} like ${} ?
I want to avoid replacing the template i read from the config, as i configure those templates on various properties and classes
ad1: For configuration i use a custom mechanism that converts a xml file into yaml which will then be used for configuration, so basically you can say its a application.yml configuration file. I cannot use custom template files in this scenario as the customer must be able to configure the template in a custom xml editor. The templates are all just a few words (like the subject of an email e.g.)
Thank you 62mkv, this seems to usually be the solution, thats why i marked it as the answer.
Anyways it wasn't the solution in my case, as it still didnt work, which is because of the way i load the config using a custom PropertySourceLoader
JAXBContext context = JAXBContext.newInstance(PICONFIG.class);
PICONFIG config = (PICONFIG) context.createUnmarshaller().unmarshal(resource.getInputStream());
YAMLFactory factory = new YAMLFactory();
//factory.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID);
ObjectMapper mapper = new ObjectMapper(factory);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String yaml = mapper.writeValueAsString(config);
PropertySourcesPlaceholderConfigurer c;
return new YamlPropertySourceLoader().load(name,new ByteArrayResource(yaml.getBytes(StandardCharsets.UTF_8)));
I now decided to just use [(#{})] for my text templates and then replace the # in the setter of the configuration bean, which seems to work so far and wasn't to big of as issue as i refactored my code to use a common configuration class for the templates
You can protect your expression by wrapping certain placeholders, thus hiding them from Spring Boot PropertyResolver mechanism:
application.properties:
test-template=[(#{'$'}{#dates.format(date, 'dd-MM-yyyy HH:mm')})]
see full working code here: https://github.com/62mkv/spring-properties-thymeleaf.
This solution is "loaned" from here: https://github.com/spring-projects/spring-framework/issues/9628
I am creating a class called FileConfig with the following annotation:
#ConfigurationProperties(locations = { "classpath:application.properties" , "${file.config.location}" })
The following line exists within 'application.properties':
file.config.location = fileinfo.yaml
Apparently, my compiler says, that the locations property has deprecated in favor of configuring the environment directly with additional locations. Can someone please help me how to configure the environment so that the variables in FileConfig are initialized using the contents of 'fileinfo.yaml' file
Using #PropertySource("classpath:testapplication.properties") instead of using the above line of code produces an error.
If I understand your question correctly, you specify the location of fileInfo.yaml file in your application.properties file. And this value should be set as location of your property class FileConfig.
I think thats not possible because SpEL expressions are not evaluated.
Here the part of the java doc from #ConfigurationProperties:
Annotation for externalized configuration. Add this to a class definition or a #Bean method in a #Configuration class if you want to bind and validate some external Properties (e.g. from a .properties file).
Note that contrary to #Value, SpEL expressions are not evaluated since
property values are externalized.
I have a Spring 3.1 application. Let's say it has an XML with the following content:
<context:property-placeholder location="classpath:somename.properties" />
<context:property-placeholder location="classpath:xxx.properties" />
I would like some.properties to be always loaded (let's assume it exists), but the xxx part of the second place holder to be replaced by some name depending on the active profile. I've tried with this:
<beans profile="xx1">
<context:property-placeholder location="classpath:xx1.properties" />
</beans>
<beans profile="xx2">
<context:property-placeholder location="classpath:xx2.properties" />
</beans>
Also, both files have properties with the same key but different value.
But it didn't work as some later bean that has a placeholder for one property whose key is defined in xx1.properties (and xx2.properties) makes Spring complain that the key is not found in the application context.
You can do:
<context:property-placeholder location="classpath:${spring.profiles.active}.properties" />
It works fine, but is perhaps not adapted when using multiple profiles in the same time.
When declaring 2 property placeholders, if the 1st one does not contain all the applications keys, you should put the attribute ignoring unresolvable = true, so that the 2nd placeholder can be used.
I'm not sure if it is what you want to do, it may if you want both xx1 and xx2 profiles be active in the same time.
Note that declaring 2 propertyplaceholders like that make them independant, and in the declaration of xx2.properties, you can't reuse the values of xx1.properties.
If you need something more advanced, you can register your PropertySources on application startup.
web.xml
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.xxx.core.spring.properties.PropertySourcesApplicationContextInitializer</param-value>
</context-param>
file you create:
public class PropertySourcesApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final Logger LOGGER = LoggerFactory.getLogger(PropertySourcesApplicationContextInitializer.class);
#Override
public void initialize(ConfigurableApplicationContext applicationContext) {
LOGGER.info("Adding some additional property sources");
String profile = System.getProperty("spring.profiles.active");
// ... Add property sources according to selected spring profile
// (note there already are some property sources registered, system properties etc)
applicationContext.getEnvironment().getPropertySources().addLast(myPropertySource);
}
}
Once you've done it you just need to add in your context:
<context:property-placeholder/>
Imho it's the best way to deal with spring properties, because you do not declare local properties everywhere anymore, you have a programmatic control of what is happening, and property source xx1 values can be used in xx2.properties.
At work we are using it and it works nicely. We register 3 additional property sources:
- Infrastructure: provided by Puppet
- Profile: a different property loaded according to the profile.
- Common: contains values as default, when all profiles share the same value etc...
I have decided to submit and answer to this as it has not yet been accepted. It may not be what you are looking for specifically but it works for me. Also note that i am using the new annotation driven configuration however it can be ported to the xml config.
I have a properties file for each environment(dev.properties, test.properties etc)
I then have a RootConfig class that is the class that is used for all the configuration. All that this class has in it is two annotations: #Configuration and #ComponentScan(basePackageClasses=RootConfig.class).
This tells it to scan for anything in the same package as it.
There is then a Configuration Containing all my normal configuration sitting wherever. There is also a configuration for each environment in the same package as the root configuration class above.
The environment specific configurations are simply marker classes that have the following annotations to point it to the environment specific properties files:
#Configuration
#PropertySource("classpath:dev.properties")
#Import(NormalConfig.class)
#Profile("dev")
The import tells it to bring in the normal config class. But when it gets in there it will have the environment specific properties set.
The project I am working at the moment uses camel as the routing framework.
When configuring camel context in spring we pass a property file that contains a bunch of global properties needed when configuring camel routes or for controlling run time behavior:
<camel:camelContext xmlns="http://camel.apache.org/schema/spring" id="my-id">
<camel:propertyPlaceholder location="my-system.properties" id="global-properties"/>
...
</camel:camelContext>
and say my-system.properties has an entry like below:
my-system.properties
# Global properties that control my-system configuration and run time
...
foo={{bar}}
...
When configuring the routes I can access foo property using the {{foo}} notation. It is also available to other beans using #PropertyInject annotation. However there is one use case in my design when a plain POJO not created by spring (an enum instead but this is not relevant) needs to access my foo property. Because this POJO it is passed the CamelContext as a method argument I find it natural to think I should be able to get the value of foo from there. However I spent a bit of time and could not figure out by myself how.
I know I can load the properties file again or even get the system property System.getProperty("bar") and everything will work but it looks like cheating to me.
There is an api on CamelContext to resolve property placeholders - its the resolvePropertyPlaceholders method:
http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/CamelContext.html#resolvePropertyPlaceholders(java.lang.String)
If your POJO is not being managed by the SpringContext I don't see any way you can automatically inject the property. Although your approach may not seem the most fancy or elegant, it has the advantage of not giving you any overhead you could have by using another injection tool.
I have a Property File like this:
frame.server.dev=mark.is.cool
frame.server.test=chris.is.cool
frame.server.qa=mitch.is.cool
frame.server.prod=cory.is.cool
I need to inject the correct value based on the environment. Since we have one ear file that we move from environment to environment, I need to do something like this:
<util:properties id="props" location="classpath:ILog-application.properties"/>
and then:
#Value ("props.frame.server.#{systemProperties.the.environment}")
private String server;
However, I cannot get systemProperties to work, nor can I get it to inject anything after a constant. Any help?
It should be
#Value ("#{props['frame.server.' + systemProperties['the.environment']]}")