Change application.properties from an HTML page - spring

I am working with Spring and have information in my application.properties that I want to update from an HTML page
Myapplication.properties
...
spring.mail.host=smtp.gmail.com
spring.mail.port=587
...
Let say we need to change the port.
Is it possible to do something like that and what is the result if a user is logged in and we made a change?
I also read this post Update property in spring environment in java code is it the right solution.
I guess if I say that we need to rebuild the appplication.properties after changing some information.

Is it possible to do something like that and what is the result if a
user is logged in and we made a change?
if i understood it right, you want to change mail port in runtime? if so :
of course this is possible, but changing the value in property file alone wouldn't result in a actual change in your system, you should know that it is your responsibility to manage the reconstruction of a new mail sender instance in which you should also consider issues like multi-threading , race-condition , etc
I propose you to use application.properties in system startup to initialize your instance, and in case of change use something like this:
taking advatage of the Changing mail configuration in runtime and singleton pattern you should probabaly reach your aim :
#Component
public class MailSender{
#Value("${spring.mail.host}")
public static String host;
#Value("${spring.mail.port}")
private static Integer port
private static JavaMailSender instance;
public static synchronized JavaMailSender getInstance(Integer port) {
if (instance == null || port!= null) {
MailSender.port = port!=null ? port: MailSender.port;
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(MailSender.host);
mailSender.setPort(MailSender.port);
return instance;
}
}
The above code is an alteration of singleton pattern in which we check whether the mail instance is null or port has new value recreate the instance otherwise if instance has already a value use that, in this way you can change port run time.
please notice that by the code above I am trying to give you some insight into the problem and you may change it based on your design.
I hope I got your purpose correctly.

First of all, after changing configuration you have to reload beans dependent on changed variables.
I would recommend you to have a look at Spring Cloud Config project.
It has the following features:
Stores configs (and changes) in Git
Can change configuration properties at runtime, and force subscribed applications to reload their context (or even dependent beans only) automatically
Despite it is not direct answer to your question (it doesn't have an UI for configuration), but it is a good reason to search UI for Spring Cloud Config instead.

Related

Injecting default "management.endpoints.web.base-path" value in Spring Boot 2.1

I'm trying to inject "management.endpoints.web.base-path" into my class's field that I need to know. I did a few hours of search for it, but all the answer is "how to customize your endpoint" by setting management.endpoints.web.base-path in the application.xml(or yaml), not "how to get a default of management.endpoints.web.base-path".
Simple code as below was expecting to grab whatever variable loaded when Spring Boot app is starting up, but nothing was retrieved in the variable.
#Autowired
private Environment environment;
public void myMethod(){
final String actuatorBase = environment.getProperty("management.endpoints.web.base-path");
}
If I define it in the application.properties I should be able to load it for sure, but I'd like to know why the default("/actuator") can't be retrieved here. However when I run the application, I had no problem to access all the actuator related functionality endpoint through /actuator.
Since it doesn't work, injecting the variable with #Value annotation also doesn't work either.
When I checked the environment variable in the debugger, I was able to see application.yaml is loaded and all the overrides variables are there, too, but not all the default "management" stuff was there.
Any idea? This app has some custom configuration, not using all the AutoConfigurer stuff, so wondering if there is specific autoconfig I need to use to make it happen.
I'm using Spring Boot 2.1.0.RELEASE.
Self answering here.
WebEndpointProperties is the one that loads all the management.endpoints.web prefix properties, so simply
#Autowired
private WebEndpointProperties webEndpointProperties;
in the class and then
String actuatorWebBasePath = this.webEndpointProperties.getBasePath();
in my method gave me a base path(/actuator).

Spring boot application properties load process change programatically to improve security

I have spring boot micro-service with database credentials define in the application properties.
spring.datasource.url=<<url>>
spring.datasource.username=<<username>>
spring.datasource.password=<<password>>
We do not use spring data source to create the connection manually. Only Spring create the database connection with JPA.(org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration)
We only provide the application properties, but spring create the connections automatically to use with the database connection pool.
Our requirement to enhance the security without using db properties in clear text. Two possible methods.
Encrypt the database credentials
Use the AWS secret manager. (then get the credential with the application load)
For the option1, jasypt can be used, since we are just providing the properties only and do not want to create the data source manually, how to do to understand by the spring framework is the problem. If better I can get some working sample or methods.
Regarding the option-2,
first we need to define secretName.
use the secertName and get the database credentials from AWS secret manager.
update the application.properties programatically to understand by spring framework. (I need to know this step)
I need to use either option1 and option2. Mentioned the issues with each option.
What you could do is use environment variables for your properties. You can use them like this:
spring.datasource.url=${SECRET_URL}
You could then retrieve these and start your Spring process using a ProcessBuilder. (Or set the variables any other way)
I have found the solution for my problem.
We need to define org.springframework.context.ApplicationListenerin spring.factories file. It should define the required application context listener like below.
org.springframework.context.ApplicationListener=com.sample.PropsLoader
PropsLoader class is like this.
public class PropsLoader implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
#Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
String appEnv = environment.getProperty("application.env");
//set new properties based on the application environment.
// calling other methods and depends on the enviornment and get the required value set
Properties props = new Properties();
props.put("new_property", "value");
environment.getPropertySources().addFirst(new PropertiesPropertySource("props", props));
}
}
spring.factories file should define under the resources package and META-INF
folder.
This will set the application context with new properties before loading any other beans.

What is advantage of using #value annotation in Spring Boot

I am new to Spring Boot and I am doing code cleanup for my old Spring Boot application.
Below code is using #Value annotation to inject filed value from properties file.
#Value("${abc.local.configs.filepath}")
private String LOCAL_ABC_CONFIGS_XML_FILEPATH;
My doubt is instead of getting value from properties file, can we not directly hardcode the value in same java class variable?
Example: private String LOCAL_ABC_CONFIGS_XML_FILEPATH="/abc/config/abc.txt"
It would be easier for me to modify the values in future as it will be in same class.
What is advantage of reading from properties file, does it make the code decoupled ?
This technique is called as externalising configurations. You are absolutely right that you can have your constants defined in the very same class files. But, sometimes, your configurations are volatile or may change with respect to the environment being deployed to.
For Example:
Scene 1:
I have a variables for DB connection details which will change with the environment. Remember, you will create a build out of your application and deploy it first to Dev, then take same build to stage and finally to the production.
Having your configurations defined externally, helps you to pre-define them at environment level and have same build being deployed everywhere.
Scene 2:
You have already generated a build and deployed and found something was incorrect with the constants. Having those configurations externalised gives you a liberty to just override it on environment level and change without rebuilding your application.
To understand more about externalising techniques read: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Here #value is used for reading the values from properties file (it could be a any environment like dev, qa, prod) but we are writing #value on multiple fields it is not recomonded so thats instead of #value we can use #configurableProperties(prefix="somevalue>) and read the property values suppose `
#configurableProperties(prefix="somevalue")
class Foo{
string name;
string address;
}
application.properties:
somevalue.name="your name"
somevalue.address="your address"
`

Mule connector config needs dynamic attributes

I have develop a new Connector. This connector requires to be configured with two parameters, lets say:
default_trip_timeout_milis
default_trip_threshold
Challenge is, I want read ${myValue_a} and ${myValue_a} from an API, using an HTTP call, not from a file or inline values.
Since this is a connector, I need to make this API call somewhere before connectors are initialized.
FlowVars aren't an option, since they are initialized with the Flows, and this is happening before in the Mule app life Cycle.
My idea is to create an Spring Bean implementing Initialisable, so it will be called before Connectors are init, and here, using any java based libs (Spring RestTemplate?) , call API, get values, and store them somewhere (context? objectStore?) , so the connector can access them.
Make sense? Any other ideas?
Thanks!
mmm you could make a class that will create the properties in the startup and in this class obtain the API properties via http request. Example below:
public class PropertyInit implements InitializingBean,FactoryBean {
private Properties props = new Properties();
#Override
public Object getObject() throws Exception {
return props;
}
#Override
public Class getObjectType() {
return Properties.class;
}
}
Now you should be able to load this property class with:
<context:property-placeholder properties-ref="propertyInit"/>
Hope you like this idea. I used this approach in a previous project.
I want to give you first a strong warning on doing this. If you go down this path then you risk breaking your application in very strange ways because if any other components depend on this component you are having dynamic components on startup, you will break them, and you should think if there are other ways to achieve this behaviour instead of using properties.
That said the way to do this would be to use a proxy pattern, which is a proxy for the component you recreate whenever its properties are changed. So you will need to create a class which extends Circuit Breaker, which encapsulates and instance of Circuit Breaker which is recreated whenever its properties change. These properties must not be used outside of the proxy class as other components may read these properties at startup and then not refresh, you must keep this in mind that anything which might directly or indirectly access these properties cannot do so in their initialisation phase or your application will break.
It's worth taking a look at SpringCloudConfig which allows for you to have a properties server and then all your applications can hot-reload those properties at runtime when they change. Not sure if you can take that path in Mule if SpringCloud is supported yet but it's a nice thing to know exists.

Spring Boot - external property not found

My application is trying to externalize all project properties, some ones will be inside my app and another ones will be in a folder somewhere in Windows.
I set up Spring to execute this way: --spring.config.location=file:///C:\Temp\config\application.properties,classpath:application.properties
As you can see, if the same property exists in both sides, application property will be kept (priority order). I noticed for example some properties such as "server.port" can be found if exists outside folder (file://) but if I create one such "common.acronym-name" my project can not find its value.
Why "server.port" has a different behaviour that one create by me? Is there any configuration I need to tell Spring Boot to see this external property in my project?
#Value("${common.acronym-name:}") //Just find it in application classpath
private String acronymEnv;
Thanks!
To simulate this error, just create a class to handle the banner, for example:
#Component
public class ShowBanner {
#Value("${spring.main.show-banner:}")
private String showBanner;
#PostConstruct
public void init() {
System.out.println(showBanner);
}
}
In this code if you set at external property file the property "spring.main.show-banner=false" the banner still shows in console if it is set before server section. When the banner should not appear. Because the property returns empty.
If I move the property after server section the banner disappears, because return false value as expected.
Keep in mind my application.properties project is empty.
By the way, Even running via Eclipse or java console it happens:
java -jar sample-1.2.3.RELEASE.jar --spring.config.location=file:///C:\Temp\config\application.properties,application.properties
Why?
Believe or not, the order of properties makes difference for external properties be found.
If I set this below order where "spring.main.show_banner" is the first one at the top, my properties can not be found. For example:
spring.main.show-banner=false
server.port=9043
server.session-timeout=1800
server.ssl.key-store=file:///C:/Temp/config/localhost.jks
server.ssl.key-store-password=localhost
server.ssl.key-password=localhost
So, If change to below order, everything works fine:
server.port=9043
server.session-timeout=1800
server.ssl.key-store=file:///C:/Temp/config/localhost.jks
server.ssl.key-store-password=localhost
server.ssl.key-password=localhost
spring.main.show-banner=false
Is there any reason for it? Spring Boot needs to have the properties in right order? Seems the "server" section must the first one in the properties.
thanks.

Resources