Spring boot: Point to different properties file from my main properties file - java

How can I point to different properties file from my main properties file depending on needs?
My main file contains different webservices types and where to find the specific file to each of them, where I will be able to access more information about that particular service.
I have a main properties file
webservices.properties:
webs1=C:\Users\yyy\webs1.properties
webs2=C:\Users\yyy\webs2.properties
webs3=C:\Users\yyy\webs3.properties
webs4=C:\Users\yyy\webs4.properties
inside the web services properties file
webs1.properties:
key1=value1
key2=value2
key3=value3
Currently my application only uses one Webservice. I call its properties file with #PropertySource in the Config class. And then use the Environment.getProperty() method whenever I want to access one of the values.
How do I make it as such I call the specific properties file of the Webservice that I'm currently using?
Config.class
#PropertySource(value = "file:src/main/resources/sddv1.properties", name = "sample.props")
#Configuration
public class Config {
#Autowired
Environment env;
#Bean
public void doStuff() {
String prop1 = env.getProperty(key1);
// I want to loop through different webservices and use the method above on each of their properties files
}
}

Use the standard application-properties or use profiles.
https://docs.spring.io/spring-boot/docs/2.6.8/reference/htmlsingle/#features.profiles
Or just override the defined properties with environment variables.
https://docs.spring.io/spring-boot/docs/2.6.8/reference/htmlsingle/#features.external-config

Related

How can I set my own property file and log file location in spring boot through my own environment variable?

I want to set both property file (myproperty.properties) and log file location (myLogFile.log) through my own environment variable name (MYENV for example).
property file name must be different from spring boot application.properties name and log file has its own name also.
Do not want to use spring.config.name and spring.config.location.
MYENV will be set to "/locationFiles" value for example. myproperty.properties file location is "/locationFiles/config"
and myLogFile.log file location is "/locationFiles/log".
I know that I can use the following code snippet for reading my environment variable.
But How do I use propertiesLocation below to read the properties data in a simple Spring boot way?
I do not know how to define a corresponding java configuration class as It seems that configuration ppties file path cannot be set in a variable.
import org.springframework.core.env.Environment;
public class MyClass {
#Autowired
private Environment env;
String propertiesLocation;
private void propertyLocation() {
this.propertiesLocation = env.getProperty("MYENV")+"/config/";
}
}
The following code snippet does not match with what I want to do as I cannot
write something like that : #PropertySource(env.getProperty("MYENV")+"/config/")
#SpringBootApplication
#PropertySource("classpath:myproperty.properties")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
I saw Environment Specific application.properties file in Spring Boot application but I does not match exactly with what I've described above.
As I want to define my own environment variable name and file names.
And I'm also looking for another way than using java -jar -Dspring.config.location=<path-to-file> myBootProject.jar as defined in Spring boot how to read properties file outside jar.
I want to know if there is an alternative way to this method.

Binding spring boot application properties to java.util.properties

I am creating a spring-boot application which also creates bean for one of the classes of an external lib, this external java bean needs java.util.properties as one of the constructor parameter. Although I can use configurationPropeties with prefix to read properties from the spring boot loaded property file and convert it to java.util.properties.However, I don't want any additional prefix in the property file. is there any other way where I can convert the spring-boot loaded env or property source to java.util.properties
here is the code for reference
#Configuration
public class AppConfig {
#ConfigurationProperties(prefix = "some.prefix")
#Bean
public Properties getProperties() {
return new Properties();
}
#Bean
public ExternalClass externalClass() throws ConfigException {
return ExternalClass.getInstance(getProperties());
}
}
the above code work nicely, but I need to add an unnecessary prefix to the properties for conversion. could someone suggest any other approach apart from adding prefix to the propeties
Take a look at this documentation. It explains property binding techniques used in spring-boot.

Spring boot - load file from outside classpath

I have to load file from outside of my classpath.
The location depends of env properties:
in dev properties I want to load file from resources folder
in prod properties I want to load file from path (/location/file)
What is the best way to do it?
A possible solution is to use configuration properties and the use of Resource. For example, define your properties like this:
#ConfigurationProperties(prefix = "app")
public class SomeProperties {
private Resource file;
// Getters + Setters
}
Then enable your configuration properties by using the #EnableConfigurationProperties annotation on any class, for example your main class:
#SpringBootApplication
#EnableConfigurationProperties(SomeProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
To configure the file location, you can use the following in development:
app.file=classpath:test.txt
And in the production environment you could use:
app.file=file:/usr/local/test.txt
And now you can just autowire the SomeProperties class within any other service. The Resource class has a getFile() method that allows you to retrieve the file, but in addition it contains several other useful methods as well.

Find message in mulitple properties files

In an application ther are multiple properties file for managing exception messages , alerts , and some others text these file like this :
- core-message.properties
- databaseException.properties
......
in Service layer maybe a database call occure and the database return a key that exist in one the properties files , and i want get the value and raise the exception messsage to user interface layer .
if i know that the key in wich properties file the code will be like this :
#Value("#{core['theExceptionKey']}")
public String excpetionMessage;
private void myMethod() {
throw new ExceptionClass(exceptionMessage);
}
i think spring can do that because when i use spring:message tag in jsp files spring does not know the key in witch file but it load the message correctly.
You can use Spring Environment abstraction for that.
First you need to add Property Source to your Java Configuration file
#Configuration
#PropertySource("classpath:/com/mypacakge/core-message.properties")
public class AppConfig {
Or if you have multiple properties files
#Configuration
#PropertySources({
#PropertySource("classpath:core-message.properties"),
#PropertySource("classpath:database.properties")
})
public class AppConfig {
Add PropertySourceConfigurer to to your Java Configuration file
#Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Now let's say that in your core-message.properties you have the following data
message.name=Hello
You can retrieve this data in any bean by autowiring Environment abstraction and then calling env.getProperty()
#Autowired
Environment env;
public void m1(){
String message = env.getProperty("message.name")` // will return Hello
Environment object provides interface to configure property sources and resolve properties. It provides convenience to read from a variety of sources: properties files, system environment variable, JVM system properties, servlet context parameters, and so on, which is very useful. For example :
environment.getSystemProperties().put("message", "Hello");
System.getProperties().put("message", "Hello");
environment.getSystemProperties().get("message"); // retrieve property
environment.getPropertySources() // allows manipulation of Properties objects
Spring Reference Documentation - Environment
To get the value of the key programmatically you can use the following:
#Autowired
private Environment env;
...
String something = env.getProperty("property.key.something");

How to read properties (or any other text) file in Java Spring MVC app?

I need to read java properties file inside my Spring MVC app but I can't find the way to do that. I tried several answers from similar question here on SO, but I was unsuccessful. I'm new to Java, and especially Spring MVC so I probably messed up something.
I'm not sure anymore that the file is being successfully deployed. I'm using Tomcat btw.
If you are using Spring 3.1+ you can use the #PropertySource annotation:
#Configuration
#PropertySource("classpath:/com/example/app.properties")
public class AppConfig {
// create beans
}
or for XML-based configuration you can use the <context:property-placeholder>:
<beans>
<context:property-placeholder location="classpath:com/example/app.properties"/>
<!-- bean declarations -->
</beans>
then you can autowire the key in the properties file using the #Value annotation:
#Value("${property.key}") String propertyValue;
Read more details in the Spring reference docs.
You can have properties files automatically loaded in Spring by using the PropertySourcesPlaceholderConfigurer.
Here is an example of configuring a PropertySourcesPlaceholderConfigurer using Spring JavaConfig:
#Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
props.setLocations(new Resource[] {
new ClassPathResource("/config/myconfig.properties"),
new ClassPathResource("version.properties")
});
}
This will load the properties from the files above on the classpath.
You can use these properties in property replacements within your application. For example, assume that there is a property in one of those files above named myprop. You could inject myprop's value into a field using the following:
#Value(${myprop})
private String someProperty;
You can also access the values of the properties by injecting Spring's Environment object into your classes.
#Resource
private Environment environment;
public void doSomething() {
String myPropValue = environment.getProperty("myprop");
}
In order to read any old file from within a web application the link that Frederic posted in the comments above provides a good explanation of the normal classloader hurdles one encounters when attempting to read files from within their war file and the solutions around it.
You can try the below code.
Add this to servelt-context.xml
<context:property-placeholder location="classpath:config.properties"/>
And to access the contents of config file in java,
#Value("${KEY}")
private String value;

Categories

Resources