第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)