Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean post processor: inject a value

I have a BeanPostProcessor bean and I want to inject two string variables with values from application.properties file. However, they are not getting injected and left with a placeholder's value.

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Value("${property1}")
    private String property1;

    @Value("${property2}")
    private String property2;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ...
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
       ...
       return bean;
    }
}

In both method values of the variables are ${property1} and ${property2}. I've tried injecting them in a regular bean and it works fine, so it definitely has to do something with the bean being BeanPostProcessor.
Is there a way to inject values somehow? I'm using Spring Boot 2.2.0.

like image 334
Никита Михайлов Avatar asked Oct 30 '25 20:10

Никита Михайлов


1 Answers

It's intended. See docs for @Value:

Note that actual processing of the @Value annotation is performed by a BeanPostProcessor which in turn means that you cannot use @Value within BeanPostProcessor or BeanFactoryPostProcessor types. Please consult the javadoc for the AutowiredAnnotationBeanPostProcessor class (which, by default, checks for the presence of this annotation).

As a workaround, you can, for example, create your post processor as bean manually inside a class marked as @Configuration and pass this value from there as a constructor parameter.

like image 184
amseager Avatar answered Nov 02 '25 10:11

amseager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!