I want to store a particular variable (String or Object) in application context in spring boot application. But I don't want to use an xml or properties file for storing it.
There will be a function which will store the data in application context. I should be able to retrieve it, modify it, delete it or add more data.
Basically I want to store data in application context after its initialization has been done.
To override your Spring Boot application properties when it's running on Kubernetes, just set environment variables on the container. To set an environment variable on a container, first, initialise a ConfigMap containing the environment variables that you want to override.
BeanFactory will create a bean object when the getBean() method is called thus making it Lazy initialization. ApplicationContext loads all the beans and creates objects at the time of startup only thus making it Eager initialization. BeanFactory interface provides basic features only thus requires less memory.
ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH.
If you create a class and put @Configuration
annotation over it, and declare some beans with @Bean
annotation, they become application managed beans.
@Configuration
public class ConfigurationClass {
@Bean("myString")
public String getString() {
return "Hello World";
}
}
Then anywhere from your code you can call AnnotationConfigWebApplicationContext.getBean("myString")
to get your bean.
Now there could be concurrency issues (as mentioned by davidxxx ). For that you can use SimpleThreadScope
. Look at this link to learn how to register it with application context and where to place that annotation (or google it).
Or if you don't want to deal with that, then a @Scope("request")
should help. The bean with @Scope("request")
would be created for every new incoming request thus it’s thread safety is guaranteed since it’s created every time a new request comes in.
As a general way, you should avoid creating stateful services.
Storing application data in the server memory makes it harder to be resilient, autonomous but also distributed and scalable.
Besides, Spring Beans are not designed to be stateful.
If you do it, you may have race conditions without the required synchronization.
About your need, if you want really to have a stateful service at startup, create your own singleton instance and synchronize the methods that should be thread safe.
Then access it from anywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With