JavaEE开发的颠覆者SpringBoot实战摘要笔记

1、注解理解

1.spring注解

1)@Configuration/@ComponentScan/@Bean注解实现java方式的配置。
@Configuration代替xml文件
@ComponentScan指定扫描范围
@Bean代替bean标签html

2)@Bean、@Component、 @Service、 @Repository 和 @Controller
这几个注解的做用相似
@Bean:表示一个方法实例化、配置或者初始化一个Spring IoC容器管理的新对象。
@Component: 自动被comonent扫描。 表示被注解的类会自动被component扫描
@Repository: 用于持久层,主要是数据库存储库。
@Service: 表示被注解的类是位于业务层的业务component。
@Controller:代表被注解的类是控制component,主要用于展示层 。
区别在于@Bean注解中不包含@Component注解,须要在类上显式写上@Component。java

@Target({ElementType.TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Component  
public @interface Service {...}

3)其余
@Autowired autowire=byType 经过类型自动注入
@Qualifier    autowire=byName 类型相同时,经过指定beanid注入,相似于@Autowired 
@PropertySource注入properties等配置文件,经过@value获取配置文件中的值
@PostConstruct 和 @PreDestroy 用于bean 的生命周期。相似于 init-method(InitializeingBean) destory-method(DisposableBean)
@Scope注解 做用域
@Lazy(true) 表示延迟初始化
@DependsOn:定义Bean初始化及销毁时的顺序
@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将做为首选者,不然将抛出异常
spring中注解的处理基本都是经过实现接口 BeanPostProcessor 来进行的
@Async异步方法调用web

4)Spring注解和JSR-330标准注解的区别
@Autowired=@Inject
@Component=@Named
SR-250标准注解
@Autowired=@Resourcespring

2.springMVC注解

1)@RequestMapping 指定URL路径
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
@RequestMapping(value="/header/id", headers = "Accept=application/json")
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
value:指定请求的实际url,支持动态uri
method:指定请求的method类型, GET、POST、PUT、DELETE等;
params:指定request中必须包含某些参数值,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html。
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。 
2)@RequestParam 绑定request请求参数
public String requestparam4(@RequestParam(value="username",required=false) String username)
value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;
required:是否必须,默认是true,表示请求中必定要有相应的参数,不然将抛出异常;
defaultValue:默认值,表示若是请求中没有同名参数时的默认值,设置该参数时,自动将required设为false。
3)@PathVariable 用于方法修饰方法参数,将修饰的方法参数变为可供使用的uri变量。数据库

@RequestMapping(value="/users/{userId}/topics/{topicId}")  
public String test(  
       @PathVariable(value="userId") int userId,   
       @PathVariable(value="topicId") int topicId)   

4)@ModelAttribute和@SessionAttributes 
SpringMVC 支持使用 @ModelAttribute 和 @SessionAttributes 在不一样的模型(model)和控制器之间共享数据。
@ModelAttribute 主要有两种使用方式,一种是标注在方法上,一种是标注在 Controller 方法参数上。
当 @ModelAttribute 标记在方法上的时候,该方法将在处理器方法执行以前执行,而后把返回的对象存放在 session 或模型属性中,
属性名称可使用 @ModelAttribute(“attributeName”) 在标记方法的时候指定,若未指定,则使用返回类型的类名称(首字母小写)做为属性名称。
控制器中的@ModelAttribute方法是在同一控制器中的@RequestMapping方法被调用以前调用的。
一个控制器能够有任意数量的@ModelAttribute方法.
5)@Responsebody与@RequestBody
@Responsebody表示该方法的返回结果直接写入HTTP response body中。通常在异步获取数据时使用
@RequestBody该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,而后把相应的数据绑定到要返回的对象上;
6)@RestController
组合了@Controller和@ResponseBody,经常使用于restful接口
@EnableWebMvc
注解会开启一些默认配置,如一些ViewResolver或者MessageConverter等。
7)@ControllerAdvice
经过@ControllerAdvice,咱们能够把控制器的全局配置放置在同一个位置,
如:@ExceptionHandler、@InitBinder、@ModelAttribute.
这对注解了@Controller的类有效。
@ExceptionHandler 用于处理器全局异常
@InitBinder 用来设置WebDataBinder,自动绑定前台请求参数到Model中
@ModelAttribute 原本的做用是绑定键值对到Model里,此处是让全局的@RequestMapping都能获取到此处设置的键值对。编程

3.@Transactional事务模块注解

eg:@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
1)propagation 事务传播行为类型
PROPAGATION_REQUIRED    若是当前没有事务,就新建一个事务,若是已经存在一个事务中,加入到这个事务中。这是最多见的选择。
PROPAGATION_SUPPORTS    支持当前事务,若是当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY    使用当前的事务,若是当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW    新建事务,若是当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED    以非事务方式执行操做,若是当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER    以非事务方式执行,若是当前存在事务,则抛出异常
PROPAGATION_NESTED    若是当前存在事务,则在嵌套事务内执行。若是当前没有事务,则执行与PROPAGATION_REQUIRED类 似的操做
2)readOnly事务只读 默认false
3)rollbackFor 回滚策略,当遇到指定异常时回滚。
4)timeout 超时时间,秒
5)isolation 事务隔离级别
DEFAULT    采用数据库默认隔离级别
READ_UNCOMMITTED    读未提交的数据(会出现脏读取)
READ_COMMITTED    读已提交的数据(会出现幻读,即先后两次读的不同)
REPEATABLE_READ    可重复读,会出现幻读
SERIALIZABLE    串行化(对资源消耗较大,通常不使用)json

4.AOP相关注解

1)spring aop:代理/CGLIB
2)Aspect 用于注解class类,标明该类为切面类,并启用AspectJ注解,注:在使用时要同@Component一块儿使用,不然不会被扫描到加入容器
@Pointcut 用于方法,标识方法是切入点并定义表达式
通知建言:@Before、@Around、@After、@AfterReturning、@AfterThrowing
执行顺序
无异常状况:Around->Before->本身的method->Around->After->AfterReturning
异常状况:Around->Before->本身的method->Around->After->AfterThrowing
@EnableAspectJAutoProxy 开启Spring对AspectJ的支持浏览器

2、Spring概要

1.POJO

Spring使用POJO(Plain Old Java Object,普通java对象)来进行企业级开发。缓存

2.Spring组成

包括:核心容器(Core Container)、AOP、消息Messaging、Web、数据访问等部分组成
1)核心容器(Core Container)
Spring-Core:核心工具类
Spring-Bean:Bean支持
Spring-Context:运行时spring容器
Spring-Context-Support:Spring容器对第三方包的集成支持
Spring-Expressing:SPEL表达式
2)AOP
Spring-AOP:基于代理的AOP支持
Spring-Aspects:基于AspectJ的AOP支持
3)Messaging消息
Spring-Messaging:对消息架构和协议的支持
4)Web
Spring-Web:提供基础的web集成功能,在web项目中提供spring支持
Spring-WebMVC:提供基于Servlet的Spring MVC
Spring-WebSocket:提供WebSocket功能
Spring-WebMVC-Portlet:提供Portlet环境支持
5)数据访问/集成
Spring-JDBC:提供JDBC支持
Spring-TX:提供对编程式事务和声明式事务的支持
Spring-ORM:提供对 对象/关系 的映射支持
Spring-OXM:提供对 对象/xml 的映射支持
Spring-JMS:提供对JMS的支持springboot

3.IOC/DI

控制反转(Inversion of control,IOC)和依赖注入(Dependency injection,DI)在Spring中是同一律念。
控制反转经过依赖注入实现,主要目的是实现”解耦“。
Spring Ioc容器(ApplicationContext)负责建立Bean,并将其注入。

4.AOP

1)AspectJ应用到java代码的过程(这个过程称为织入),对于织入这个概念,能够简单理解为aspect(切面)应用到目标函数(类)的过程。
对于这个过程,通常分为动态织入和静态织入,动态织入的方式是在运行时动态将要加强的代码织入到目标类中,这样每每是经过动态代理技术完成的,
如Java JDK的动态代理(Proxy,底层经过反射实现)或者CGLIB的动态代理(底层经过继承实现),Spring AOP采用的就是基于运行时加强的代理技术.
ApectJ采用的就是静态织入的方式,即编译期织入,Spring没有采用这种方式。
2)Spring的两种动态代理:Jdk和Cglib
java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。
而cglib动态代理是利用asm开源包,对代理对象类的class文件加载进来,经过修改其字节码生成子类来处理。
由于cglib是继承,因此该类或方法最好不要声明成final 。
a.若是目标对象实现了接口,默认状况下会采用JDK的动态代理实现AOP 
b.若是目标对象实现了接口,能够强制使用CGLIB实现AOP 
c.若是目标对象没有实现了接口,必须采用CGLIB库,spring会在JDK动态代理和CGLIB之间自动转换。

5.Scope种类

1)Singleton:一个Spring容器中,只有一个Bean实例,是Spring的默认配置
2)Prototype:每次调用都建立一个Bean实例
3)Request:Web项目中,对于每一个Http Request新建一个实例
4)Session:Web项目中,对于每一个Http session新建一个实例
5)GlobalSession:在portal中起做用

6.Profile

Profile为不一样环境下使用不一样的配置,提供支持。
eg:@Profile("dev")/@Profile("proc")/context.getEnvironment().setActiveProfiles("dev"); 指定使用开发环境配置

7.@Enable*注解

@Enable*的实质是经过@import注解引入配置类

    @Target(ElementType.TYPE)  
    @Retention(RetentionPolicy.RUNTIME)  
    @Import(SchedulingConfiguration.class)  
    @Documented  
    public @interface EnableScheduling {  
    }

@EnableAspectJAutoProxy 开启对AspectJ的支持
@EnableAsync 开启对异步方法的支持
@EnableScheduling 开启对计划任务的支持
@EnableWebMvc 开启对webMvc的支持
@EnableConfigurationProperties 开启对@ConfigurationProperties注解配置bean的支持
@EnableJpaRepositories开启对Spring Data JPA Repository的支持
@EnableTransactionManagement 开始对注解事务的支持
@EnableCaching 开启对注解缓存的支持

8.其余

Spring事件(Application Event)为Bean与Bean之间的通讯提供了支持。
Spring Aware接口能够从Spring容器中获取容器信息。
Spring经过在配置类中设置@EnableAsync开启异步任务支持
在Bean方法上使用@Async注解这是一个异步任务
Spring经过在配置类中设置@EnableScheduling开启计划任务支持
在Bean方法上使用@Scheduled注解这是一个计划任务。可使用cron fixDelay fixRate等。
@Conditonal条件注解
@Conditonal(*)根据是否知足条件来建立Bean

9.Spring测试支持

@RunWith/@ContextConfiguration/@ActiveProfiles

@RunWith(SpringJUnit4ClassRunner.class) //1  
@ContextConfiguration(classes = {TestConfig.class}) //2  
@ActiveProfiles("prod") //3  
public class DemoBeanIntegrationTests {  
    @Autowired //4  
    private TestBean testBean;  
    @Test //5  
    public void prodBeanShouldInject(){  
        String expected = "from production profile";  
        String actual = testBean.getContent();Assert.assertEquals(expected, actual);  
    }  
}

①SpringJUnit4ClassRunner在JUnit环境下提供
Spring TestContext Framework的功能。
②@ContextConfiguration用来加载配置
ApplicationContext, 其中classes属性用来加载配置类。
③@ActiveProfiles用来声明活动的profile。
④可以使用普通的@Autowired注入Bean。
⑤测试代码

3、SringMVC概要

1.在Servlet 2.5及如下的时候只要在web.xml下配置<servlet>元素,指定DispatcherServlet便可
2.在Servlet3.0+无web.xml时,须要实现WebApplicationInitializer接口
3.服务器端推送技术
客户端向服务端发送请求,服务端会抓住这个请求不放,等有数据更新的时候才返回给客户端;
当客户端接收到消息后,再向服务端发送请求,周而复始。这种方式的好处是减小了服务器的请求数量,大大减小了服务器的压力。
@RequestMapping(value="/push",produces="text/eventstream")
这里使用输出的媒体类型为text/eventstream,这是服务器端SSE(Server Send Event服务端发送事件)的支持。
4.测试支持
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources")
public class TestControllerIntegrationTests {...}
5.工做过程
第1步:浏览器发送指定的请求都会交给DispatcherServlet,他会委托其余模块进行真正的业务和数据处理 
第2步:DispatcherServlet会查找到HandleMapping,根据浏览器的请求找到对应的Controller,并将请求交给目标Controller 
第3步:目标Controller处理完业务后,返回一个ModelAndView给DispatcherServlet 
第4步:DispatcherServlet经过ViewResolver视图解析器找到对应的视图对象View 
第5步:视图对象View负责渲染,并返回到浏览器

4、springboot要点

1.配置

springboot必须设置parent为springboot的parent,引入springboot默认配置。  
    <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>1.5.2.RELEASE</version>  
        <relativePath></relativePath>  
    </parent>  
引入web支持  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
添加springboot插件  
        <plugins>  
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>  
        </plugins>  
建立启动类  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
import org.springframework.context.annotation.ComponentScan;  
import org.springframework.context.annotation.Configuration;

@Configuration  
@EnableAutoConfiguration  
@ComponentScan  
public class Application {  
      public static void main(String\[\] args) {  
          SpringApplication.run(Application.class, args);  
      }  
        
}

2.调试插件

1)springloader
a.插件方式 只对后台代码起做用(不须要重启,真正的热部署),对前台jsp的修改不起做用。
                  是之后台进程的方式工做的,须要在任务管理器中手动杀掉javaw.exe

<plugin>  
	<groupId>org.springframework.boot</groupId>  
	<artifactId>spring-boot-maven-plugin</artifactId>  
	<dependencies>    
		<dependency>    
			<groupId>org.springframework</groupId>    
			<artifactId>springloaded</artifactId>    
			<version>1.2.4.RELEASE</version>  
		</dependency>    
	</dependencies>    
	<executions>    
		<execution>    
			<goals>    
				<goal>repackage</goal>    
			</goals>    
			<configuration>    
				<classifier>exec</classifier>    
			</configuration>    
		</execution>    
	</executions>  
</plugin>

b.在项目中引入springloader的jar包,添加VM启动参数。
2)devtools 对java文件的修改会重启服务,jsp不会重启。

        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-devtools</artifactId>  
        </dependency>

devtools使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另外一个ClassLoader加载会更改的类,称为 restart ClassLoader 
,这样在有代码更改的时候,原来的restart ClassLoader 被丢弃,从新建立一个restart ClassLoader,因为须要加载的类相比较少,因此实现了较快的重启时间(5秒之内)。

3.简介

1)SpringBoot项目只需经过java–jar xx.jar来运行。工程中可以使用mvn spring-boot:run运行
2)SpringBoot CLI是Spring Boot提供的控制台命令工具,用于生成基本工程,Springboot提供了大量的starter来简化配置。
3)@SpringBootApplication是Spring Boot项目的核心注解,主要目的是开启自动配置。
实质:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
    Class<?>[] exclude() default {};
    String[] excludeName() default {};
}
4)@EnableAutoConfiguration让Spring Boot根据类路径中的jar包依赖为当前项目进行自动配置。
Spring Boot会自动扫描@SpringBootApplication所在类的同级包及下级包里的Bean.
使用@SpringBootApplication注解的exclude参数能够关闭自动配置。
@SpringBootApplication(exclude ={DataSourceAutoConfiguration.class})
5)src/main/resources下新建一个banner.txt,能够设置个性化的启动logo。
http://patorjk.com/software/taag
6)咱们能够经过Spring提供的@ImportResource来加载xml配置
@ImportResource({"classpath:somecontext.xml","classpath:another-context.xml"})
7)SpringBoot默认使用Logback做为日志框架。
经过在application.properties中设置spring.profiles.active=prod来指定活动的Profile。
8)@EnableAutoConfiguration

@Target(ElementType.TYPE)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Inherited  
@Import({ EnableAutoConfigurationImportSelector.class,AutoConfigurationPackages.Registrar.class })  
public @interface EnableAutoConfiguration {  
    Class<?>\[\] exclude() default {};  
    String\[\] excludeName() default {};  
}

使用@Import注解导入配置。
EnableAutoConfigurationImportSelector使用SpringFactoriesLoader.loadFactoryNames方法来扫描具备
META-INF/spring.factories文件的jar包, 而的spring-boot-autoconfigure-1.3.0.x.jar里就有一个
spring.factories文件, 此文件中声明了有哪些自动配置。

@ConditionalOnBean: 当容器里有指定的Bean的条件下。 @ConditionalOnClass: 当类路径下有指定的类的条件下。 @ConditionalOnExpression: 基于SpEL表达式做为判断条件。 @ConditionalOnJava: 基于JVM版本做为判断条件。 @ConditionalOnJndi: 在JNDI存在的条件下查找指定的位置。 @ConditionalOnMissingBean: 当容器里没有指定Bean的状况下。 @ConditionalOnMissingClass: 当类路径下没有指定的类的条件下。 @ConditionalOnNotWebApplication: 当前项目不是Web项目的条件下。 @ConditionalOnProperty: 指定的属性是否有指定的值。 @ConditionalOnResource: 类路径是否有指定的值。 @ConditionalOnSingleCandidate: 当指定Bean在容器中只有一个, 或者虽然有多个可是指定首选的Bean。 @ConditionalOnWebApplication: 当前项目是Web项目的条件下。 9)SpringBoot推荐使用Thymeleaf做为模板引擎. 在Spring Boot里,模板引擎的页面默认是开启缓存的,若是修改了页面的内容,则刷新页面是得不到修改后的页面的. 所以,咱们能够在application.properties中关闭模板引擎缓存

相关文章
相关标签/搜索