Spring Boot学习记录手册
[TOC]
1 Spring 发展历史
- spring 1.x时代,全部使用XML注解.
- spring 2.x时代,由于jdk1.5发展注解,Spring有了较为简单的注解.实际使用多为注解+XML.
- spring 3.x~~4.x,注解越来越完善,并且spring4.x还提供了java config形式.
- 子项目越来越多,社区越来越活跃.
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官网,可以直接下载一个项目,作为初始的示例项目:
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;@SpringBootApplicationpublic 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. ** 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@Configurationpublic @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.登陆.
6.1.4 配置项
Spring在src/main/resources下有application.properties 文件进行项目各种参数的配置. Idea也有所有参数的提示功能.比较方便. 如配置以下参数:
banner.charset=UTF-8server.port=8000server.context-path=/HelloWorld
6.1.5 spring boot starter pom
详情请见spring github地址:
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文件位置, 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的这种方式比较适合少量,简单的属性,如果是大量的参数配置,:
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);
@Componentpublic class LoadAdditionalProperties implements ApplicationListener{ 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.