4

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.

  • 1
    Have you tried injecting them into _another_ class, and then make that class a dependency of the `BeanPostProcessor`? It could be that spring's creating the bean post processor _before_ whatever it is which is retrieving the `@Value`. – BeUndead Nov 28 '19 at 12:16
  • Just tried it, the values are still populated with placeholders. However, there's a workaround - I made a @ConfigurationProperties bean for these props and it's autowiring to the bpp bean with already filled values. Thanks for the hint! – Никита Михайлов Nov 28 '19 at 12:25

1 Answers1

4

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.

amseager
  • 5,795
  • 4
  • 24
  • 47