I write Spring Boot application. I use file application.properties to contains configuration of database. But now I want to get properties from application.yml which contains:
rest:
response: RESPONSE
#RestController
public class MyController {
#Value("${rest.response}")
private String restResponse;
#GetMapping("/foo")
public ResponseEntity<String> register() {
return restResponse;
}
}
Directory resources contains application.properties and application.yml. Why I cannot import properties from .yml?
If you are using 'application.yml' , if the RESPONSE that is read from application.yml contains characters such as + , - etc , put the value inside single inverted commas otherwise it won't be read properly(since it is mapped to a string variable).
check that org.yaml:snakeyaml:1.26 is in classpath (or spring-boot-starter is in dependencies)
Related
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
I am looking for help involving a spring application ( someone else's design ) that uses kafka consumers and producers.
The design allows for a config.properties file that contains an entry like so:
kafkaAddress=10.10.10.12:9093,10.10.10.11:9093,10.10.10.10:9093
Such config is picked up by some kind of spring bean code like this...
Java code...
private String kafkaAddress;
public String getKafkaAddress() {
return kafkaAddress;
}
public void setKafkaAddress(String kafkaAddress) {
this.kafkaAddress = kafkaAddress;
}
And it shows up in a Properties object I see with debugger.
"kafkaAddress" -> "10.10.10.12:9093,10.10.10.11:9093,10.10.10.10:9093"
The code passes the Properties object to constructor of the Kafka client
I thought this all happened through the design of spring and matching config "kafkaAddress" with a String of matching name kafkaAddress
Well I want to config for ssl such things as ...
ssl.truststore.location=C:\some\path\kafka.client.10.10.10.11.truststore.jks
ssl.truststore.password=mySecretWord
I put such things in config but what do i put for my setter and getter?
I can't put String ssl.truststore.location, right?
In config.properties I use ...
ssl_truststore_password=mySecretPassword
In setters and getters in MyConsumerConfig.java file I use...
public void setSsl_truststore_password(String ssl_truststore_password ) {
this.ssl_truststore_password = ssl_truststore_password;
}
public String getSsl_truststore_password() {
return this.ssl_truststore_password;
}
Before call to constructor .java file I ...
if(StringUtils.isNotEmpty(myConsumerConfig.getSsl_truststore_password())) {
consumerProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG,
onlineConsumerConfig.getSsl_truststore_password());
}
The SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG is defined in package org.apache.kafka.common.config.SslConfigs ...
public static final String SSL_TRUSTSTORE_PASSWORD_CONFIG "ssl.truststore.password"
The spring framework links the "ssl_truststore_password" in the config file to the getters and setters such as ...
MyConsumerConfig.setSsl_truststore_password(String ssl_truststore_password)
In my spring boot application I have the following controller
#RestController(value = "ProjectController")
#CrossOrigin(origins = {"${app.api.settings.cross-origin.urls}"})
public class ProjectController {
// some request mapping methods
}
The property app.api.settings.cross-origin.urls is already a key having comma separated valid urls in application.properties file like
app.api.settings.cross-origin.urls=http://localhost:3000, http://localhost:7070
This approach works till I have only single value like
app.api.settings.cross-origin.urls=http://localhost:3000 but not for comma separated values.
The origins field inside #CrossOrigin is of type String[] still it does not convert into String[] automatically.
I mean there should be some way to achieve this provided by the framework. Not a work around.
I can achieve using comma separated urls from properties files using #Value into a List<String> or String[] as a field inside a #Configuration class like below
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Value("${app.api.settings.cross-origin.urls}")
private String[] consumerUiOrigins;
#Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/api/**")
.allowedOrigins(consumerUiOrigins);
}
}
But this would be a global configuration having application wide applicability. I want to stick to the more fine grained #CrossOrigin annoation based CORS configuration.
So I put my question clearly below.
Is it possible to inject comma separated value from properties file as String[] using property plcaholer expression (${*}) into spring annotation fields having the same type i.e. String[] ????? If yes then how??? If no then can we tweak some core framework classes to achieve this??? Anyone please help....
P.S. - Please do not mark my question as duplicate of Use Spring Properties in Java with CrossOrigin Annotation or in Spring-Config XML
My question is more on usage of property placholder expressions inside spring annotation fields having multi element type like String[] and less on the configuration of CORS in spring applications.
Try doing as below in application.properties:
app.api.settings.cross-origin.urls="http://localhost:3000","http://localhost:7070"
I have written queries in property file. I want to read the property file in to one class with annotations in spring boot. How can i read it? And is there any better approach for writing queries in spring boot project?
If you add your properties in application.properties file, you can read them inside the spring boot classes like:
#Service
public class TwitterService {
private final String consumerKey;
private final String consumerKeySecret;
#Autowired
public TwitterService(#Value("${spring.social.twitter.appId}") String consumerKey, #Value("${spring.social.twitter.appSecret}") String consumerKeySecret) {
this.consumerKey = consumerKey;
this.consumerKeySecret = consumerKeySecret;
} ...
You can annotate fields in your components by #Value("${property.name}")
Else, you can use Properties Object in java.util package.
For example, i have a mode property, which values are dev or prod, i can use it in my beans as follow :
#Value("${mode:dev}")
private String mode;
The other approach is by using :
Properties pro = new Properties();
pro.load(this.getClass().getClassLoader().getResourceAsStream());
You can use #PropertySource to read the properties from a file and then pass them to a bean. If you have a file called "queries.properties" that has a property like:
query1: select 1 from foo
Then your config might look like:
#PropertySource("classpath:queries.properties")
#Configuration
public class MyConfig {
#Bean
public DbBean dbBean(#Value("${queries.query1}") String query) {
return new DbBean(query);
}
}
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;