SpringBoot編程思想

Spring Boot的特性web

  1)、建立獨立的Spring應用spring

  2)、直接嵌入Tomcat、Jetty或Undertow等Web容器(不須要部署WAR文件)安全

  3)、提供固化的starter依賴,簡化構建配置和依賴管理app

  4)、當條件知足時自動地裝配Spring或第三方類庫框架

  5)、提供運維(Production-Ready)特性,如指標信息(Metrics)、健康檢查及外部化配置運維

  6)、絕無代碼生成,而且不須要XML配置ide

即約定大於配置,簡化開發。spring-boot

  

爲何說是獨立的Spring應用?this

  SpringBoot應用無需再向傳統的JavaEE應用那樣,將應用打包成WAR文件或者JAR文件,並部署到JavaEE容器中運行(雖然其也支持)。spa

  SpringBoot應用採用嵌入式Web容器,獨立於外部容器,對應用生命週期擁有徹底自主的控制。

在傳統的Spring應用中,外置容器須要啓動腳本將其引導(如ContextLoaderListener),隨其生命週期回調執行Spring上下文的初始化。比較表明性的是Spring Web中的

ContextLoaderListener和Web MVC中的DispatcherServlet,前者利用ServletContext生命週期構建Web ROOT Spring應用上下文,後者結合Servlet生命週期建立DispatcherServlet

的Spring應用上下文。不管何種方式,均屬於被動的回調執行,這也是爲何它們沒有完整的應用主導權的緣由。

  當Spring Boot出現嵌入式容器啓動方式後,嵌入式容器則稱爲應用的一部分,從本質上來講,它屬於Spring應用上下文的組件Beans,這些組件和其餘組件均由自動裝配

特性Spring Bean定義(BeanDefinition),隨Spring應用上下文啓動而註冊並初始化。而驅動Spring應用上下文啓動的核心組件則是Spring Boot核心API SpringApplication,

因此是Spring應用,也能夠稱爲SpringBoot應用。

 

理解自動裝配

  SpringBoot引導類:

 
 
//@ImportResource 導入xml配置文件
@SpringBootApplication
public class SpboApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpboApplication.class, args);
    }
}

@SpringBootApplication註解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan  //SpringBoot會自動掃描當前類的同級包以及下級包裏的Bean,並自動注入到Spring容器中
public @interface SpringBootApplication {   

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be
     * applied.
     * @return the class names to exclude
     * @since 1.3.0
     */
    String[] excludeName() default {};

    /**
     * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
     * for a type-safe alternative to String-based package names.
     * @return base packages to scan
     * @since 1.3.0
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
    String[] scanBasePackages() default {};

    /**
     * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
     * scan for annotated components. The package of each class specified will be scanned.
     * <p>
     * Consider creating a special no-op marker class or interface in each package that
     * serves no purpose other than being referenced by this attribute.
     * @return base packages to scan
     * @since 1.3.0
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class<?>[] scanBasePackageClasses() default {};

}

能夠看到@SpringBootApplication註解是一個組合註解

 至關於@Configuration、@EnableAutoConfiguration@ComponentScan的累加

  @EnableAutoConfiguration:激活Spring Boot自動裝配機制

  @ComponentScan:激活@Component的掃描

  @Configuration:聲明被標註爲註解類

同時,其屬性方法帶有@AliasFor註解,用於橋接其餘註解的屬性。

 

 @EnableAutoConfiguration註解能夠幫咱們自動載入應用程序所須要的全部默認配置

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be
     * applied.
     * @return the class names to exclude
     * @since 1.3.0
     */
    String[] excludeName() default {};

}

此註解有兩個重要的註解:

  @Import:向Spring容器中導入了EnableAutoConfigurationImportSelector組件

  @AutoConfigurationPackage:自動配置包

 

1):@AutoConfigurationPackage:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

發現仍是依靠Import註解導入了AutoConfigurationPackages.Registrar組件,其代碼爲:

    /**
     * {@link ImportBeanDefinitionRegistrar} to store the base package from the importing
     * configuration.
     */
    @Order(Ordered.HIGHEST_PRECEDENCE)
    static class Registrar implements ImportBeanDefinitionRegistrar {

        @Override
        public void registerBeanDefinitions(AnnotationMetadata metadata,
                BeanDefinitionRegistry registry) {
            register(registry, ClassUtils.getPackageName(metadata.getClassName()));
        }

    }

其做用是將主配置類(@SpringBootApplication)的所在包及其子包裏面的組件掃描到Spring容器中。好比帶有@Entity註解的組件,由

 @AutoConfigurationPackage掃描並加載,而平時經常使用的@Controller/@Service/@Component/@Repository這些註解是由ComponentScan

來掃描並加載的。

2):EnableAutoConfigurationImportSelector組件

  會在Spring啓動的時候掃描全部jar路徑下的META-INF/Spring.factories,而後篩選出以EnableAutoConfiguration爲key的數據,加載到IOC

容器中,最後會默認加載113個默認的配置類,實現自動配置功能。

 

 

理解約定大於配置

  即經過約定來減小配置。約定優於配置是一個簡單的概念。系統、類庫、框架應該假定合理的默認值,而非要求提供沒必要要的配置。

大部分狀況下,使用框架提供的默認值會讓你的項目開發起來效率更快。如:

在Spring Boot中,當咱們導入一個spring-boot-starter-web後。就會自動地幫咱們導入Spring MVC的相關依賴(包括Json支持的Jackson和數據校驗的HibernateValidator)

和一個內置的Tomcat容器,這使得開發階段能夠直接經過main方法或者JAR包獨立運行一個WEB項目。由於Spring Boot約定,當你導入了一個spring-boot-starter-web後,

就約定了你是一個web開發環境。

 

獲取屬性配置文件的Properties

  在常規的Spring環境下,注入properties文件裏的值要經過@PropertySource指明properties文件的位置,而後經過@Value注入值,在SpringBoot裏,只須要在application.properties

 定義屬性,直接使用@Value注入便可。可是若是咱們的配置比較多的話,則@Value會注入不少次。因此SpringBoot還提供了基於類型安全的配置方式,經過@Configurationproperties

 將properties屬性和一個Bean及其屬性關聯,從而實現類型安全的配置。

// 將前綴爲self的屬性配置和bean關聯起來,使用時直接依賴注入此bean便可
@Component
@ConfigurationProperties(prefix = "self")
public class SelfProperties {
    private String name;
    private Long age;
    get set...
}
相關文章
相關標籤/搜索