Spring Boot學習記錄手冊<1>

Spring Boot學習記錄手冊

[TOC]

1 Spring 發展歷史

  1. spring 1.x時代,全部使用XML註解.
  2. spring 2.x時代,由於jdk1.5發展註解,Spring有了較爲簡單的註解.實際使用多爲註解+XML.
  3. spring 3.x~~4.x,註解越來越完善,並且spring4.x還提供了java config形式.
  4. 子項目越來越多,社區越來越活躍.

2 Spring核心項目

核心項目也就是Spring生態圈的基礎項目.

2.1 核心容器,IOC支持

  • Spring-Core:核心工具類,Spring其他模塊都會用到.
  • Spring-Beans:Spring定義的Bean(POJO)的支持.
  • Spring-Context:運行時java容器.
  • Spring-Context-Support:Spring容器對第三方包的集成支持.
  • Spring-Expression:功能豐富強大的表達式語言SpEL是類似於OGNL和JSF EL的表達式語言,能夠在運行時構建複雜表達式,存取對象屬性,對象方法調用等.

2.2 AOP支持

  • Spring-AOP:基於代理的AOP支持.
  • Spring-Aspects:基於AspectJ的AOP支持.

2.3 Message支持

  • Spring-Messaging:對消息架構和協議的支持,沒用過,不瞭解.應該是個公用jar.

2.4 Web

  • Spring-Web:提供基礎web功能.
  • Spring-WebMVC:提供基於servlet的springMVC.
  • Spring-WebSocket:顧名思義.
  • Spring-Webmvc-Portlet:提供Portlet支持.

2.5 數據操作

  • SpringJDBC:JDBC支持.
  • Spring-TX:事務支持.
  • Spring-ORM:ORM支持.
  • Spring-OXM:提供對象/XML映射技術支持.
  • Spring-JMS:JMS支持.

3 Spring生態項目

以Spring爲核心展開的各種集成第三方框架的項目.

  • Spring-Boot:快速開發.約定大於配置.
  • Spring-XD:用來簡化大數據開發的框架.
  • Spring-cloud-data-flow:對其大數據產品Spring XD進行了完全的重構.
  • Spring-Cloud:爲分佈式系統開發提供工具集.
  • Spring-Data:對主流的關係型和NoSQL數據庫的支持.
  • Spring-Integration:通過消息機制對企業集成模式(EIP)的支持.
  • Spring-Batch:簡化,優化大量數據的批處理操作.
  • Spring-Security:比shiro更重的安全框架.
  • Spring-Hateots:基於Hateots原則簡化REST服務開發.
  • Spring-Social:對社交網絡API的集成,如新浪微博.
  • Spring-AMQP:對基於AMQP的消息支持.
  • Spring-Mobile:對手機設備進行檢測,爲不同的設備返回不同的頁面.
  • Spring-For-Android:爲安卓提供消費REST API的能力.
  • Spring-Web-Flow:基於SpringMVC的,嚮導流程式的WEB應用功能.太複雜,放棄,沒用過.
  • Spring-WebService:SOAP/WEB服務.一般用CXF,沒用過這個.
  • Spring-LDAP:顧名思義.
  • Spring-Session:提供API來管理集羣的用戶session.
  • Spring-Flo:一個JavaScript庫,可嵌入HTML5 visual builder for pipelines and simple graphs.沒用過,沒興趣.
  • Spring-KAFKA:Spring對apache kafka的集成,簡化.

其他社區項目和孵化的項目不予關注.不過spring-scala很值得圍觀.

4 Spring框架原則

Spring有四大原則: 1.使用POJO進行輕量級和最小侵入式開發. 2.通過依賴注入和基於接口編程實現鬆耦合. 3.通過AOP和約定進行聲明式編程. 4.通過使用AOP和template減少模式化代碼.

5.Spring Boot基礎

5.1 核心功能

1.獨立運行的Spring項目,可以以jar形式進行獨立運行,只需要 java -jar xxx.jar 來運行. 2.內嵌Tomcat,Jetty,Undertow,可以不用war就能進行部署. 3.提供父POM文件,參考項目:spring-boot-starter-web. 4.自動化配置.減少配置量. 5.準生產的應用監控,spring boot提供了基於http,ssh,telnet對運行狀態的項目的監控. 6.無代碼生成和XML配置.從spring4開始官方建議使用註解和java config.

5.2 示例項目

進入Spring官網,可以直接下載一個項目,作爲初始的示例項目:http://start.spring.io/

6.Spring Boot核心

6.1基本配置

6.1.1 入口類,@SpringBootApplication

SpringBoot通常有一個入口函數用以啓動SpringBoot項目.函數所在類名一般是"項目名+Application".

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

@SpringBootApplication是Spring Boot的核心註解.

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;

/**
 * Indicates a {@link Configuration configuration} class that declares one or more
 * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
 * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience
 * annotation that is equivalent to declaring {@code @Configuration},
 * {@code @EnableAutoConfiguration} and {@code @ComponentScan}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 1.2.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "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
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
	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 {};

}

通過觀察註解的源代碼,可以發現@SpringApplication主要是融合了@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan

而實際上@SpringBootConfiguration是對@Configuration的一次封裝.

package org.springframework.boot;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Configuration;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

而@EnableAutoConfiguration就比較有意思了,其源碼如下:

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

	String ENABLED_OVERRIDE_PROPERTY = "spring.boot.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 {};

}

其功能是:有此註解,SpringBoot會自動掃描類路徑/pom依賴下的spring jar,並自動進行初始化的配置.

@ComponentScan 則會掃描@SpringBootApplication註解所在的同級目錄以及下級目錄的所有的Bean,並註冊到Spring容器.這點要注意.

6.1.2 關閉指定的自動配置項

通過查看源碼可得知有exclude功能. 可以設置的參數參見Spring-boot-autoconfigure jar包(org.springframework.boot.autoconfigure下). 示例:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration;

@SpringBootApplication(exclude = {AopAutoConfiguration.class})
public class DemoApplication {

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

6.1.3 修改項目啓動CMD窗口的Banner

1.在min/resource下新建一個banner.txt文件. 2.登陸http://patorjk.com/software/taag,將生成的字符串放到txt中.

6.1.4 配置項

Spring在src/main/resources下有application.properties 文件進行項目各種參數的配置. Idea也有所有參數的提示功能.比較方便. 如配置以下參數:

banner.charset=UTF-8
server.port=8000
server.context-path=/HelloWorld

6.1.5 spring boot starter pom

詳情請見spring github地址: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters

6.1.6 導入spring xml配置

一些特殊情況下需要用到xml.可以用以下方式進行xml配置 @ImportResource(locations={"classpath:application-bean.xml"}) mportResouce有兩種常用的引入方式:classpath和file.classpath方式如上,file方式如 locations= {"file:d:/application-bean.xml"};

具體做法就是新建一個配置類,確保可以被springboot掃描到,如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(locations={"classpath:application-bean.xml"})
//@ImportResource(locations={"file:d:/application-bean.xml"})
publicclass ConfigClass {

}

6.2 其他一些額外的配置

Spring boot允許用properties,yaml,cmd命令行參數作爲外部配置.

6.2.1 基於properties常規的屬性配置[少量參數方式]

在spring環境下,注入properties文件裏值的方式,需要使用@Property指明properties文件位置,再使用@Value注入值.而在spring boot裏,這個過程再次被簡化. 我們只需要在application.properties裏面定義好,直接在程序使用@Value就可以了. 如下所示,我們定義兩個參數

book.name="spring"
book.price="50"

獲取參數

	@Value("${book.name}")
    private String bookName;

    @Value("${book.price}")
    private String bookPrice;

6.2.2 基於properties類型安全的屬性配置[推薦使用的參數方式]

如上所示,使用@Value的這種方式比較適合少量,簡單的屬性,如果是大量的參數配置,推薦使用以@Configuration與properties文件相關聯的方式.如下所示:

book.name="spring"
book.price=50

使用註解@Configuration和properties相關聯,注意註解使用的prefix參數.

package com.example;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "book")
public class BookParams {

    private String bookName;
    private Double price;

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

6.2.3 加載其他properties文件

spring boot 1.5 對於註解@ConfigurationProperties,去掉了locations參數,也就無法在註解上指定其他properties文件.對於這情況.有如下解決方法: 1.入口類處進行處理

new SpringApplicationBuilder(Application.class)
    .properties("spring.config.name=application,mine")
    .run(args);

2.入口類監聽ApplicationEnvironmentPreparedEvents或者寫一個EnvironmentPostProcessor

監聽寫法如下:

new SpringApplicationBuilder(Application.class)
    .listeners(new LoadAdditionalProperties())
    .run(args);
@Component
public class LoadAdditionalProperties implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private ResourceLoader loader = new DefaultResourceLoader();

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        try {
            Resource resource = loader.getResource("classpath:mine.properties");
            PropertySource< ?> propertySource = new PropertySourcesLoader().load(resource);
            event.getEnvironment().getPropertySources().addLast(propertySource);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

}

3.就在application.properties裏寫吧.

6.3 Profile 配置

Profile和maven的profile是一樣的概念. 全局Profile配置使用application-{profile}.properties (application-prod.properties) 通過在application.propertis中設置spring.profile.active=prod來指定活動的profile.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章