Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify properties resolved by Spring before their injection into beans

I need to provide support for external preperties decryption in Spring application. I planned to use a mechanism from spring-cloud-config, which is triggered after the Environment is ready and add decrypted properties with higher precedence. Unfortunately it heavily relies on Spring Boot bootstrap mechanism which emits ApplicationEnvironmentPreparedEvent. Looking into the Spring Framework code the environment and context creation is highly coupled and it would be rather hard to run my own code between that. The application I am working with is a large, multi module "standard" Spring MVC application and I would not like to convert it into Spring boot application right now.

Question:

How could I execute my code after the environment was created and before the context creation (to modify properties before they will be injected into "normal" beans) in Spring (not Spring Boot) application?

Alternative question:

Is there any other way to get control over properties being injected into beans (for modify values originally resolved by Spring)?

like image 708
Marcin Zajączkowski Avatar asked Oct 20 '25 02:10

Marcin Zajączkowski


2 Answers

You can create a custom ApplicationContextInitializer which adds decryption or whatever to the PropertySources of your choice.

We do something similair in one of the application I currently develop. After loading some custom properties from files and databases we wrap all the available PropertySources in a EncryptablePropertySource because several properties are encrypted (We use the Jasypt library for that).

like image 95
M. Deinum Avatar answered Oct 21 '25 16:10

M. Deinum


Use @Value("${propname}") annotation on a setter method, instead of using on the field.

You can write code to handle transform/validate the property in the setter method, and then assign to the field.

like image 29
Manish Maheshwari Avatar answered Oct 21 '25 16:10

Manish Maheshwari