Search code examples
javaspring-bootnullyamlsnakeyaml

Spring @ConfigurationProperties doesn't inject anything, field stays null


I am trying to inject values to fields like this:

@Component
@ConfigurationProperties("paypal")
public class Paypal
{
    private List<List<List<String>>> deleterequest;

    public List<List<List<String>>> getDeleterequest()
    {
        return deleterequest;
    }

    public void setDeleterequest(List<List<List<String>>> deleterequest)
    {
        this.deleterequest = deleterequest;
    }


    private String date;

    public String getDate()
    {
        return date;
    }

    public void setDate(String date)
    {
        this.date = date;
    }
}

Note: The Paypal bean itself is successfully loaded and not null. Reading values with @Value works fine in that class. My main class is also annotated with:

@EnableConfigurationProperties

But both date and deleterequest stays null in this code:

@Autowired
private Paypal propsPayPal;

this.propsPayPal.getDeleterequest(); //returns null (no NPE!)
this.propsPayPal.getDate(); //returns null (no NPE!)

In the Spring Java Config I wrote:

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
{
    PropertySourcesPlaceholderConfigurer o = new PropertySourcesPlaceholderConfigurer();
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource(Constants.PROPERTIES_FILE_NAME));
    o.setProperties(yaml.getObject());
    return o;
}

@Bean
public Paypal paypal()
{
    return new Paypal();
}

and my application.yml looks like this:

paypal:
    date: Datum
    deleterequest:
    -
        -
            - Typ
            - Allgemeine Abbuchung
        -
            - Status
            - Abgeschlossen

Any help?

EDIT: I've figured out that when I create a new Spring project (just to test this issue) with an AnnotationConfigApplicationContext (which is used in my main program) as Context, it doesn't inject any values. Using a ConfigurableApplicationContext (via. SpringApplication.run(...)) works perfectly fine, variables will get injected. I have to get it to work on a AnnotationConfigApplicationContext though.


Solution

  • Solution was to switch to a ConfigurableApplicationContext. I used a AnnotationConfigApplicationContext which doesn't support this feature.