Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply dynamic properties to a bean at runtime

Assume I have a bean DialogBox, with properties for height and width:

public class DialogBox {
 int x;
 int y;
 ...
}

In my applicationContext.xml I would define properties as reasonable defaults:

<bean id="dialogbox" class="DialogBox">
  <property name="x" value="100"/>
  <property name="y" value="100"/>
</bean>

We have multiple clients that use the dialogBox bean, and each wants a custom value for x and y. One route we have discusses is having multiple properties files, one for each client, and have the client id map to the proper file, for example client 123 would map to dialogbox_123.properties:

dialogbox_123.properties:
x=200
y=400

Then at runtime when the bean is requested, spring would look to see if a custom properties file exists for the client, and use those properties, otherwise use the defaults. I am aware of the PropertyOverrideConfigurer, but AFAIK this only works when the context is started so will not work for our purposes. Is there an existing facility in spring to achieve this, or can someone recommend another way?

like image 595
Rich Kroll Avatar asked Jan 05 '10 18:01

Rich Kroll


People also ask

Can we create a bean at runtime?

This can be done without restarting the application at runtime when Loading and Removing bean in Spring Application. If the client code needs to register objects which are not managed by Spring container, then we will need to work with an instance of BeanDefinition. Here, We have used the following dependencies.

Which annotation is used to inject property values into beans?

A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.

How do you override a Spring property?

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.


1 Answers

  1. Use FactoryBean (as already suggested) to customize instantiation.
  2. set scope="prototype" on the bean, so that each time an instance is required, a new one should be created.
  3. In case you want to inject the prototype bean into a singleton bean, use lookup-method (Search for lookup-method here)

I'm not sure if this would fit your case though. Another suggestion would be:

In @PostConstruct methods of your various "clients" set the properties as desired on the already injected dialog window. Like:

public class MyDialogClient {
    @Autowired
    private Dialog dialog;

    @PostConstruct
    public void init() {
        dialog.setWidth(150); //or read from properties file
        dialog.setHeight(200);
    }
    ...
}

Again, in this case, you can play with the scope atrribute.

like image 90
Bozho Avatar answered Sep 28 '22 00:09

Bozho