springboot開發(fā)白皮書-配置類

springboot偏好使用java class類型的來引入配置屬性,也就是將properties、json、YML格式的配置文件讀取到class中生成全局bean來使用,當(dāng)然考慮到歷史原因,還保留讀取xml格式資源文件的能力。

屬性配置到一個(gè)class中

  1. 創(chuàng)建一個(gè)獨(dú)立的class,包含全部的屬性,通過@Configuration注解該class聲明為配置類,然后再通過@Value將resources中的配置文件中的屬性值注入該類,或者通過@ConfigurationProperties(prefix = "oss")將某個(gè)屬性對(duì)象下的子屬性注入該類對(duì)應(yīng)的同名字段
@Data
@Configuration
@ConfigurationProperties(prefix = "oss")
public class OssConf {
    @Value("${key1}")
    private String key1;
    @Value("${key2}")
    private String key2;

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}
  1. 導(dǎo)入xml格式配置文件
    通過@ImportResource聲明可以將xml格式的配置文件導(dǎo)入進(jìn)容器。
    bean的配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="helloService" class="com.chentongwei.springboot.service.HelloService"></bean>
</beans>

通過xml導(dǎo)入將bean注冊到容器

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class Springboot02ConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02ConfigApplication.class, args);
    }
}
  1. 自動(dòng)配置
    可以通過@EnableAutoConfiguration聲明自動(dòng)配置,但是建議在每個(gè)配置class上以@Configuration明確聲明配置類。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容