第1种 使用@Value("${属性key}")
第2种 使用 @PropertySource(prefix = "属性的前缀")
第3种使用@PropertySources+@PropertySource
第1种
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
@Data
public class ValueProperties {
// @Value("other.name") //此方式是指定name的值为other.name
@Value("${other.name}")
public String name;
}
第2种
@Data public class OtherProperties { private String name; private String desc; }
配置类:
/** * @Description: 加载properties文件 * 从应用加载的properties的匹配规则 */ @Configuration //注释掉有,从应用加载的properties文件中找,主要多个properties注意顺序和覆盖问题 //@PropertySource("application2.properties") //@1 public class OtherPropertiesConfiguration { /** * 默认是找程序加载的properties文件,此应用就是application.properties */ @Bean @ConfigurationProperties(prefix = "other") // @ConfigurationProperties(prefix = "other2") 对应@1 public OtherProperties otherProperties(){ return new OtherProperties(); } }
application.properties的内容
other.name=other other.desc=come on
第3种
@Data public class HerPropeties { private String name; private String desc; }
@Data public class MyPropeties { private String name; private String desc; }
配置类
@Configuration @PropertySources({ @PropertySource("my.properties"), @PropertySource("her.properties") }) public class PropertiesConfiguration { @Bean @ConfigurationProperties(prefix = "my") public MyPropeties myPropetiest(){ return new MyPropeties(); } @Bean @ConfigurationProperties(prefix = "her") public HerPropeties herPropetiest(){ return new HerPropeties(); } }
her.properties的内容:
her.name=angle her.desc=chinese
my.properties的内容
my.name=allen my.desc=java
测试类
@SpringBootApplication public class SpringbootPropertiesApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringbootPropertiesApplication.class, args); System.out.println(context.getBean(MyPropeties.class)); System.out.println(context.getBean(HerPropeties.class)); System.out.println(context.getBean(OtherProperties.class)); System.out.println(context.getBean(ValueProperties.class)); } }
测试结果
MyPropeties(name=allen, desc=java)
HerPropeties(name=angle, desc=chinese)
OtherProperties(name=other, desc=come on)
ValueProperties(name=other)