首頁 > 軟體

SpringBoot bean依賴屬性設定詳細介紹

2022-09-28 14:00:33

建立實體類

@Data
public class Cat {
    private String name;
    private Integer age;
}
@Data
public class Mouse {
    private String name;
    private Integer age;
}

組態檔application.yml使用固定格式為屬性注入資料

cartoon:
  cat:
    name: "圖多蓋洛"
    age: 5
  mouse:
    name: "泰菲"
    age: 6

業務類定義業務功能bean,在引導類通常使用@Import匯入,解耦強制載入bean

使用@EnableConfigurationProperties註解設定使用屬性類時載入bean

@Data
//當載入CartoonCatAndMouse類時將CartoonProperties類載入成bean,不用不載入,解耦合
@EnableConfigurationProperties(CartoonProperties.class)
public class CartoonCatAndMouse {
    private Cat cat;
    private Mouse mouse;
    private CartoonProperties cartoonProperties;
    public CartoonCatAndMouse(CartoonProperties cartoonProperties){
        this.cartoonProperties = cartoonProperties;
        cat = new Cat();
        cat.setName(cartoonProperties.getCat()!=null && StringUtils.hasText(cartoonProperties.getCat().getName()) ? cartoonProperties.getCat().getName() : "tom");
        cat.setAge(cartoonProperties.getCat()!=null && cartoonProperties.getCat().getAge()!=null ? cartoonProperties.getCat().getAge() : 3);
        mouse = new Mouse();
        mouse.setName(cartoonProperties.getMouse()!=null && StringUtils.hasText(cartoonProperties.getMouse().getName()) ? cartoonProperties.getMouse().getName() : "jerry");
        mouse.setAge(cartoonProperties.getMouse()!=null && cartoonProperties.getMouse().getAge()!=null ? cartoonProperties.getMouse().getAge() : 4);
 
    }
    public void play(){
        System.out.println(cat.getAge()+"歲的"+cat.getName()+"和"+ mouse.getAge()+"歲的"+mouse.getName()+"打起來了");
    }
}

將業務功能bean執行需要的資源抽取長獨立的屬性類,設定讀取組態檔的資訊

@Data
//類與組態檔繫結
@ConfigurationProperties(prefix = "cartoon")
public class CartoonProperties {
    private Cat cat;
    private Mouse mouse;
}

測試:

@SpringBootApplication
//當執行時將CartoonCatAndMouse類載入成bean,不允許不載入
@Import(CartoonCatAndMouse.class)
public class Demo15SpringbootBeanpropertiesApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Demo15SpringbootBeanpropertiesApplication.class, args);
        CartoonCatAndMouse bean = ctx.getBean(CartoonCatAndMouse.class);
        bean.play();
    }
}

總結:

  1. 業務bean的屬性可以為其設定預設值
  2. 當需要設定時通過組態檔傳遞屬性
  3. 業務bean應儘量避免設定強制載入,而是根據需要匯入後載入,降低spring容器管理bean的強度

到此這篇關於SpringBoot bean依賴屬性設定詳細介紹的文章就介紹到這了,更多相關SpringBoot bean依賴屬性設定內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com