简体   繁体   中英

Spring boot auto-configuration and properties

I have 2 modules in my project app & starter. Starter contains @Configuration and tells how a bean of ServiceFoo should be created.

@Configuration
@EnableConfigurationProperties(FooServiceConfiguration.class)
public class StarterFoo {

    @Bean
    public ServiceFoo defaultBean(FooServiceConfiguration conf){
      new ServiceFooImpl(conf.getName(), conf.getNumber());
    }

}

I have another configuration class in my starter.

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("Foo")
public class FooServiceConfiguration {
    private String name;
    private int number;
    // + accessors
}

in my starter I have application.yml which has

Foo:
 name: DefaultName
 number: 101

starter is configured to be auto-configured

META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=StarterFoo

I want to have opinion on my config about number and user will never worry and override that number. I want users to override name in my config.

As soon as I create application.yml in app (blank file) the effect of starter's config (from application.yml from starter) goes away.

How can I partially override this config from app which is defined in starter ?

There can only be a single Boot configuration file with a specific name regardless of where on the classpath they're located (ie, you can have application-test.yml and application.yml , but only one of each), and "closer" to runtime (the fat jar) overrides more distant (embedded jars). Boot doesn't merge the contents, it simply only reads a single application.yml .

The simplest way to accomplish what you want is to use Java normally and initialize the class variables with your default values:

private String name = "DefaultName";
private int number = 101;

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