Global application context/environment runtime properties - spring

There are some properties which are not read from a configuration file but are acquired from some remote resources and are constant, for example, user ID from a database. They are global in app context (it means that each application context has same properties with different values).
I expected something like context.setProperty or context.setGlobalProperty or context.getEnvironment().setProperty, but I couldn't find such methods.
My current solution is to create a singleton lazy bean which is initialized during application initialization and then it can be autowired into any bean. But it seems to me that this is not the best method.

It's not a good idea to change environment during runtime.
Environment is also bean in context, so your solution is ok.
Also you can use static container with dynamic variables and fill it during runtime

Related

Is it possible to prevent a bean from being created?

I have an external dependency that instantiates a bean having a #Value property. Of course, if the property is not present, the application will crash (no default value).
Would it be possible that, under a certain profile, the bean is not created at all? Or inject at runtime the property to prevent the crash?

Spring-Boot: share an object between components

I have a custom object which I like to share between different Spring-Boot components (e.g. WebHandler, Authenticator, Filter).
Maybe the easiest way is a static object in the main-class but thats not very elegant.
Whats the most common way to do it?
The whole point of spring as a container is to manage your objects.
Now statics do not have a well defined lifecycle ( when exactly this object gets created, who disposes it when the application gets closed, etc)
Speing answers all these questions by using thecdependency injection techniques. If you're already using spring then you should define this 'shared object' as a spring bean (by default it will have scope singleton just like static object that you've proposed but managed by spring container which is better - it will manage the lifecycle of the object by itself)
Then given the classes that must be dependent of the object are beans by themselves you can inject that bean:
class MySharedObject {}
class MyWebHandler implementsWebHandler {
private final MySharedObject mySharedObject;
public MyWebHandler(MySharedObject mySharedObject) {
this.mySharedObject = mySharedObject;
In addition to the lifecycle management this way allows easy unit testing of classes that use the shared object (like 'MyWebHandler' in this case) - now uou can create a stub/mock of the shared object and pass it into the handler - something that cannot really be easily done when using statics
So in summary if you can use spring and define it as a bean - by all means do so, the usage of statics is discouraged if you already have a dependency injection container
If you have shared object first of all it should not contain any state as differents components can change it and also it should be thread safe.
It is fine to reuse it across all components via #Autowired annotation but you need to be sure that it is threadsafe. Spring bean scope singleton is not thread safe out of box it dependes how you write the code.
You can use as static method but it dependes on logic which you have and if those component has an dependency on another objects and if they need to in spring IOC.

How to provide custom logic to search for bean if it cannot be found in Spring Context

If the Spring context cannot find a bean referred to from my xml I want to be able to provide some custom logic (ie look in another Spring Context or create the bean programmatically) before a BeanNotFoundException (whatever the expection is) is thrown.
You can use the BeanFactoryPostProcessor to define your beans dynamically (click on the link for an explanation).
Alternatively if you want to act on your bean in a lazy manner (instead of at app startup), which I strongly recommend not to do since you will have bugs related to the state of you beans config that is not visible at compile time: Anyway, you can surely add to your ApplicationContext a custom singleton : instead of calling getBean() from spring, if nothing was found, your class will be called to respond which bean corresponds to a bean name, and you will indirectly have the opportunity to handle BeanNotFoundException
See a post about the second (not recommended) solution here : How to add Properties to an Application Context

Real use case of proptotype scope of spring beans

Waht is a real example for such kind of stuff? I have already looked through this post, but the answers to this post seem inconclusive to me. Also there is an advice: "As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans" - from spring reference, but why do we need our services to be stateful? We can just share this state as a simple dto among services' calls.
One popular use of it is to associate separate instance of a bean to each HTTP session.
Consider your have a bean class called UserConfig. You can set this bean with prototype scope, and configure such that each new HTTP session has its own UserConfig bean instance. (Spring MVC has its own scope called "session" for this purpose, but the concept is similar)
Also the user can change your site configuration, and the changed state is saved on its own instance of the bean (as opposed of altering the global single instance if you set it into singleton scope)

Spring Instantiation and 'unused beans'

I'm working on a project which means customising an existing application (JasperServer 3.7.1) which is implemented in Spring 2.5.6 (plus a host of other Spring frameworks).
The application consists of a host of applicationContext*.xml containing the bean definitions which when wired together by Spring bring the app to life - I think it's a typical Spring app configuration as although it my first experience using Spring, it seems all quite well put together and follows a lot of the examples I have seen on the web and in books..
Because I'm actually modifying an existing application, changing beans like filterChainProxy (because we have our own security model ,for example) I'm wary of changing the actual config files that come with the product - instead, where possible, I'd prefer to add extra appContext config files to the existing ones which override existing beans (ie leave the original config in tact, as much as possible).
This I've managed to do by creating beans implementing BeanFactoryPostProcessor which on pre-bean initialisation allow me to change the existing property values/bean references to custom ones. This all seems to be working fine.
My query is, say I had a bean with a property that referred to another bean, and my overrider bean changed that reference to my own version of bean, will Spring still instantiate the bean that is no longer referred to ? The reason for asking obviously is that some of these unused beans may be taking up resources, which may be an unwanted overhead.
Thanks in advance
I'm not sure I follow your example, but it might help to clarify a few things.
Generally, Spring will instantiate a bean for every non-abstract bean definition in the context (this is ignoring things like non-singleton bean scopes, but I'll ignore that for the purposes of this explanation). If multiple bean definition files are used, and some bean names are duplicated, then some definitions will be overridden by others. so far, so good, this seems to be what you wanted.
Once the bean definitions have been established, and any duplicated dealt with, then Spring will then instantiate a bean for each of those definitions. If you have changed the definition of BeanA so that it no longer refers to BeanB, but instead refers to BeanC, but the definition of BeanB still exists, then BeanB will still be instantiated, even if it's not being used.
If that example is not representative of your question, then please elaborate.

Resources