Properties and env are always null

I find it difficult to load properties from my properties file. I am trying to load a property into my configuration class, which is listed below.

package dk.fitfit.budget.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;


@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

    @Autowired
    private Environment env;

    @Value("${snot:test}")
    private String snot;

    public ApplicationConfig() {
        logger.info("Application config loaded!");  // Displays as expected
        logger.info("snot: {}", snot);              // snot: null
        logger.info("env: {}", env);                // env: null
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

If I change the file name (application.properties) or "@PropertySource (" classpath: application.properties ")", I get an error when the file is not present. It is so clear that it is loading (to some extent).

I, at least, expected to see the standard string "test" entered in the snot variable. But even this has not been done. I can not autwire Environment or ... not sure if there is a relationship.

The contents of my application.properties is as follows.

snot=snog

My application.properties file is placed in src / main / resources /.

Has anyone understood what I'm doing wrong?

+4
2

- . , Spring - . , , env snot - , null .

+5

Spring ( ) new, , . , @Value , @Configuration, .

, : @PostConstruct. , DI bean:

@PostConstruct
public void log() {
    logger.info("Application config loaded!");  // Displays as expected
    logger.info("snot: {}", snot);              // snot: null
    logger.info("env: {}", env);                // env: null
}
+4

All Articles