简体   繁体   中英

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)?

You can create a custom ApplicationContextInitializer which adds decryption or whatever to the PropertySource s 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 PropertySource s in a EncryptablePropertySource because several properties are encrypted (We use the Jasypt library for that).

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.

In the mean time I have found customizeContext method in ContextLoader which reads defined ApplicationContextInitializer s. It is executed after the environment was created and before the context is reloaded, so decryption in an initializer should work (at least in the base case):

ConfigurableEnvironment env = wac.getEnvironment();
(...) 
customizeContext(sc, wac);
wac.refresh();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM