1. 程式人生 > >三十四、Springboot 自動裝配

三十四、Springboot 自動裝配

(一)自動裝配介紹   在以前的Spring中,我們需要使用一個依賴,比如(Druid),那麼我們在引入這個依賴以後,還需要在XML配置檔案中配置一大堆類及其屬性。但是在Springboot中,我們只需要在application.yml中定義一些屬性就可以實現 Druid 的正常使用,他所用到的技術就是自動裝配

(二)自動裝配的實現   我們的案例是自動裝配Person物件,實現自動裝配有兩種方式:

public class Person {
    private Long id;
    private String name;
    private Integer age;
}

1、使用註解方式

/**
 * {@link org.pc.domain.Person}自動裝配
 * 註解 @ConditionalOnProperty :
 * matchIfMissing = true:不存在時依然啟用
 * matchIfMissing = false:不存在時不啟用;存在時,必須 person.enabled=true才能啟用
 */
@Configuration
@ConditionalOnProperty(prefix = "person", name = "enabled", havingValue = "true", matchIfMissing = true)
public class PersonAutoConfiguration {

    @ConfigurationProperties(prefix = "person")
    @Bean
    public Person person(){
        return new Person();
    }
}

2、將標記 @Configuration (上一種方式中標記@Configuration註解)的Spring Configuration Class 放置在相對於class-path下的 META-INF/spring.factories 檔案中 (1)自定義Spring Configuration Class

/**
 * {@link org.pc.domain.Person}自動裝配
 * 註解 @ConditionalOnProperty :
 * matchIfMissing = true:不存在時依然啟用
 * matchIfMissing = false:不存在時不啟用;存在時,必須 person.enabled=true才能啟用
 */
@ConditionalOnProperty(prefix = "person", name = "enabled", havingValue = "true", matchIfMissing = true)
public class PersonAutoConfiguration {

    @ConfigurationProperties(prefix = "person")
    @Bean
    public Person person(){
        return new Person();
    }
}

(2)將自定義配置類放置在相對於class-path下的 META-INF/spring.factories 檔案中   在resources包下建立META-INF包,新建spring.factories檔案:

#自動裝配類(上面一個類是 自動裝配類,下面一個類是待自動裝配的類,=\ 代表換行)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.pc.autoconfigure.PersonAutoConfiguration

(三)測試自動裝配是否成功

@RestController
public class PersonController {
    private Person person;
    @Autowired
    public PersonController(Person person) {
        this.person = person;
    }
    @GetMapping("/person")
    public Person getPerson(){
        return person;
    }
}