简体   繁体   中英

Spring boot @ConfigurationProperties not working

I'm using @ConfigurationProperties for auto configuration of properties. My code is working in IDE. But when I run the jar in command line, it is not working.

Configuration class:

@Configuration
@ConfigurationProperties(prefix="location")
public class Location {

private String base;

public String getBase() {
    return base;
}

public void setBase(String base) {
    this.base = base;
}
}

Main class:

@SpringBootApplication
@EnableConfigurationProperties(Location.class)
@EnableAutoConfiguration
public class Application {

public static void main(String[] args) {

    SpringApplication.run(Application.class, args);
}
}

application.yml:

location:
 base: c:\test

If I autowire Location class, I see an instance created. But there is not property set. The code is not entering setBase() method.

The application prints this in the console.

AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' 
annotation found and supported for autowiring

Make sure that application.yml file is in the root of your classpath, usually it's put in the resources folder.

The fact that the setBase() method is not called suggests that your application.yml file is not being found. Spring looks in the root of your classpath for the application.yml file.

The comment from M. Deinum is correct saying that your duplicated annotations will result in 2 spring beans for Location class. However, as you say you managed to autowire the bean without getting an error it suggests that your Location class isn't in a package that is found by spring when it's scanning for beans. If there were 2 beans then you'd get an error when you autowired it. By default spring will scan use the package where the @SpringBootApplication is as the base. It will then look in this package and all sub packages.

If your package structure is like this...

myapp.main
    Application.java
myapp.config
    Location.java

Then you need to add scanBasePackages="myapp" to the @SpringBootApplication annotation.

Also change your main class and remove the @Enable.. annotations. ie:

@SpringBootApplication(scanBasePackages="myapp")
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

As nothing worked with yaml, I had to change to property file and use

@PropertySource({"classpath:application.properties"})

for the spring to identify the properties file

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