I am setting my database properties from an external file and am trying to do the same for the active profile, but am not having any luck.
In app.properties if tried: spring.config.location= C:\\run\\secrets\\test but that did not work.
In the same config file that I have the database properties being read in I've tried:
#Component
#Configuration
#PropertySource(value={"file:/run/secrets/file.properties"}, ignoreResourceNotFound = true)
public class AppProperties {
#Resource
private Environment env;
#Bean
public Properties props(){
Properties props = new Properties();
props.setProperty("spring.profiles.default", env.getRequiredProperty("spring.profiles.active"));
//props.put("spring.profiles.active", env.getRequiredProperty("spring.profiles.active"));
return props;
}
}
In my external file I've tried both
spring.profiles.active=dev and spring.profiles.default=dev
Nothing seems to work.
If I understand correctly, your file is on Disk C.
So, in windows, the external file path should be like this:
#PropertySource(value={"file:///C:/run/secrets/file.properties"}, ignoreResourceNotFound = true)
Related
I am using Spring boot 2.5.4. I have written web application. Now i am facing issue with application.properties file variables. If i am changing existing value, In code old value is been read, newly defined object is not coming.
Find the below application.properties file
spring.datasource.url=jdbc:mysql://XXXXXXXXXXX:3306/test
spring.datasource.username=user
spring.datasource.password=XXXXXXXXXXXXXXXX
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
# Config Variables
ml.url=https://google.com/ml/entities
main.url=https://xxxx.com/staging/mainfile
and application config java file
#Component
public class ApplicationConfig {
#Value("${ml.url}")
public String mlurl;
#Value("${main.url}")
public String mainurl;
#PostConstruct
public void initThat(){
that = this;
}
}
reading variable in code as
#RequestMapping("/readfile")
#RestController
public class AppointmentResource {
private static Logger S_LOGGER = LogManager.getLogger( AppointmentResource.class );
#Autowired
private ApplicationConfig applicationConfig;
#GetMapping(value = "/websiteUrl",produces = MediaType.APPLICATION_JSON_VALUE)
public String getProduct() {
String websiteUrl = applicationConfig.mlurl;
S_LOGGER.info("website url is " + websiteUrl);
return websiteUrl;
}
}
After compiling for few times. Then i changes ml.url to https://google.com/prod/entities/test
but in code still i am getting as https://google.com/ml/entities.
Can anyone help in getting latest changes from application.properties
I am struck here. Help
I fixed it. It was picking from the folder config. which i created for different environments
I have a external yaml properties files that I have loaded and I want to retrieve. But the suggested way to get YAML is like so:
#Value("${some.var}");
and this isn't working.
I am loading the files in like so:
#Bean
public static PropertySourcesPlaceholderConfigurer properties() {
String userHome = System.getProperty('user.home');
ArrayList<String> locations = new ArrayList<String>(
Arrays.asList(
"${userHome}/.boot/beapi_server.yml",
"${userHome}/.boot/beapi.yml",
"${userHome}/.boot/beapi_db.yml",
"${userHome}/.boot/beapi_api.yml"
)
);
Collections.reverse(locations);
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
for (String location : locations) {
String finalLocation = location.toString();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new FileSystemResource(finalLocation));
propertySourcesPlaceholderConfigurer.setProperties(Objects.requireNonNull(yaml.getObject()));
}
return propertySourcesPlaceholderConfigurer;
}
The actuator/configprops also don't show the properties.
What am I doing wrong? A bit frustrated.
Ok so I figured it out and wanted to post the answer for others to see.
After loading the external files into your PropertySources, you can now access them through #ConfigurationProperties annotation by referencing the YML structure prefix head and then just access the properties directly through assignment
// 'tomcat' if the top level prefix in my yml file
#ConfigurationProperties(prefix="tomcat")
class something{
ArrayList jvmArgs
}
Now lets look at my yml:
tomcat:
jvmArgs:
-'-Xms1536m'
-'-Xmx2048m'
-'-XX:PermSize=256m'
-'-XX:MaxPermSize=512m'
-'-XX:MaxNewSize=256m'
-'-XX:NewSize=256m',
-'-XX:+CMSClassUnloadingEnabled'
-'-XX:+UseConcMarkSweepGC'
-'-XX:+CMSIncrementalMode'
-'-XX:+CMSIncrementalPacing'
-'-XX:CMSIncrementalDutyCycle=10'
-'-XX:+UseParNewGC'
-'-XX:MaxGCPauseMillis=200'
-'-XX:MaxGCMinorPauseMillis=50'
-'-XX:SurvivorRatio=128'
-'-XX:MaxTenuringThreshold=0'
-'-server'
-'-noverify'
-'-Xshare:off'
-'-Djava.net.preferIPv4Stack=true'
-'-XX:+EliminateLocks'
-'-XX:+ExplicitGCInvokesConcurrent'
-'-XX:+UseBiasedLocking'
-'-XX:+UseTLAB'
And we see this will directly assign the value jvmArgs to the ArrayList JvmArgs in the class above. Simple.
So, rather simple and elegant solution once you know how... but knowing how is the trick isn't it :)
i'm using yaml configuration too. in my case, you have to create a configuration class then you can autowired it.
this is my code:
PdfConfig.java
#Component
#ConfigurationProperties(prefix = "pdf")
#EnableConfigurationProperties
public class PdfConfig {
private String licensePath;
private Watermark watermark;
// setter getter goes here
}
PdfServiceImpl.java
#Service
public class PdfServiceImpl implements PdfService {
#Autowired
private PdfConfig pdfConfig;
}
application-local.yml
#### Pdf Config ####
pdf:
license-path: classpath:license/development/itextkey.xml
watermark:
image-path: classpath:static/img/logo.png
opacity: 0.2f
enabled: true
If you want to learn about setting spring yaml, you can go to this link spring-yaml
Hope this helped!
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);
}
}
#Configuration
#PropertySource("classpath:test.properties")
public class Config {
#Bean
public CompactDisc cd(#Value("#{ systemProperties['artist']}") String artist) {
HotelCalifornia hotelCalifornia = new HotelCalifornia();
hotelCalifornia.setArtist( artist);
return hotelCalifornia;
}
#Bean
public CdPlayer player(CompactDisc cd) {
CdPlayer player = new CdPlayer();
player.setCd(cd);
return player;
}
}
The property is in the test.properties file. I cant get the property "artist" from the systemProperties.But I can get it if i use #autowired to instantiate a environment bean.How can i deal with it?
you dont have to do anything. the spring recognizes property is first it will check in the system properties, then the class level properties and then properties initialized using property placeholder.
so try using #Value("${artist}") provided you have artist set in the systems property somehow.
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