Access java variable in application.properties - spring

Is there a way to set value from java class to application.properties
For Example
// Constants.java
public interface Constants {
String APP_NAME = "demo_app";
}
# application.properties
app.name=${Constants.APP_NAME}
obviously above example of application.properties will not work. But I want to access a constant variable's value from java class into application.properties.

Related

How to define a conditional property with a variable sub property name

I have a configuration property class that contains a map. The map is filled with values from a yml file. the structure looks like this.
config:
variable_sub_key_a:
key_a: 1234
key_b: 1234
variable_sub_key_b:
...
The configuration class looks like:
#Configuration
public class Configuration{
private Map<String, KEY> config= new HashMap<>();
}
I would like that the configuration class is only initialized by spring when the config element exists in the yml file. My problem is that a part of the property name can vary. So i can't use #ConditionalOnProperty. I tried it with different contidional-annotations but haven't found out how i could define a conditional that checks only that the property starts with config.* . Any hints how i can do this?

Default values for missing maven properties when expanded in spring application.properties

If a property #property.absent# defined in application.properties cannot be expanded (it is not defined in pom.xml), the bound value is the literal #property.absent#. Is there an easy way to override this with custom defaults (e.g. null), esp. in auto-configuration in conjunction with #ConfigurationProperties?
application.yml file:
test:
property: #property.absent#
Configuration properties class:
#ConfigurationProperties("test")
public class TestConfigurationProperties {
private String property = "your default value";
//Getters and Setters
}

application.properties spring boot value injection

I'm working on the REST API with spring boot. I want to use git in my project. in the file application.properties I have the database Url, username and password that I do not want to push on git. I don't know how can I create a file which contains my database configuration and how to inject those configurations in the application.properties .
application.properties
## Server Properties
server.port= 5000
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= jdbc:mysql://localhost:3306/MyApp?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username= user
spring.datasource.password= pass
Spring picks up configuration properties not only from the application.properties but also from command line arguments, JAVA System-properties or from environmental-variables.
See complete list here: Spring Externalized Configuration.
So - for reference - you can keep the properties in the application.properties file with some default values (like in your example) in order to let other users know what kind of properties they can set for your application.
But instead of setting your real values there, you can either pass the variable to your application as arguments, like
-Dspring.datasource.username=user -Dspring.datasource.password= pass
or you can set them as environmental variables.
You can even create multiple configuration with different settings. If Spring cannot find a variable in the current configuration, then it will pick it up from application.properties (or from the other sources - see above)
first you should add application.properties to .ignore file like this
application.properties
if you will just connect to database you won't need to inject values by hand you just write it in application.properties
but if you want to put values in properties file and use it in Application
package com.microservice.test.limitservice;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties("limit-service")
public class Configuration {
private int minimum;
private int maximum;
public int getMinimum() {
return minimum;
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getMaximum() {
return maximum;
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
}
and how to inject it simply
#Autowired
private Configuration configuration;
the application.properties file could be like this
limit-service.minimum=56333445
limit-service.maximum=6500
you should notice that it start with as example limit-service
and #ConfigurationProperties("**limit-service**")
And if you want to store your configuration in application.properties secure
you can see this link Spring Boot how to hide passwords in properties file

how to write a value into application.properties in spring boot

I already saw Write/Update properties file value in spring
In Spring boot
How to write a value into application.properties in spring boot?
application.properties:
ews.batch_type=
ews.batch_dat=
...other fields
I want:
application.properties:
ews.batch_type=ALL
ews.batch_dat=20170222
...other fields
Thanks
After you give some more information I guess you want to define default values. The application.properties is still static but you can do something in your Application to handle missing properties.
You can define default values
// Gets the Value of "ews.batch_type" or "ALL" if no property is defined
#Value("${ews.batch_type:ALL}")
private String batchType;
public static String getDate() {
return "..."; // <- the date you want
}
#Value("#{ config['ews.batch_dat'] ?: T(yourClass).getDate() }")
private String date;

Passing environment values in application.properties

I am new to spring-boot and trying to pass the Backend credentials as environment values into my application.properties.
To set the Environment values in Tomcat and created a setenv.bat and setenv.sh
Location: \apache-tomcat-7.0.53-windows-x64\apache-tomcat-7.0.53\bin
set username="ABC"
set password="xyz"
These Environment values are getting set and i am able to print it also using
#Autowired
private Environment env;
String userName = env.getProperty("username");
String pwd = env.getProperty("password");
and trying to access these values in application.properties like
spring.datasource.username=${username}
spring.datasource.password=${password}
but that is not working.
I tried the different way and mentioned the environment variables name in setEnv.bat like
set spring.datasource.username="ABC"
set spring.datasource.password="xyz"
i was hoping that Spring Boot will read these values from Env and pass it to data source so that i do not have to mention explicitly in application.properties but that is also not working. please note, i do not have any bean.xml file and i am doing pure annotation based development. Any inputs here..
If I understand correctly, then you want to access the variables written in your application.properties file
This can be done in many ways, but one simple way is to do following in your .java file :
#PropertySource("classpath:application.properties")
class AppConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
#Test
public void test_fetch_property() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.registerShutdownHook();
Environment environment = context.getBean(Environment.class);
String strWhoami = environment.getProperty("whoami.name").toString();
assertThat(strWhoami,equalTo("\"John Doe\""));
}
The whoami.name is the property that is fetched from application.properties file and tested
application.properties file:
#----------------------------------------------------------
# Show your self
#----------------------------------------------------------
whoami.name="John Doe"
I hope that this can help a bit

Resources