为什么80%的码农都做不了架构师?>>>   hot3.png

Upgrade to Spring Boot 1.4

Spring Boot 1.4 is a big jump, and introduced lots of new test facilities and aligned with the new technology stack, such as Spring framework 4.3 and Hibernate 5.2 and Spring Security 4.1, etc.

Spring Boot 1.4

New starter:spring-boot-starter-test

Spring Boot 1.4 brings a new starter for test scope, named spring-boot-starter-test.

Use the following:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>

Instead of:

<dependency><groupId>com.jayway.jsonpath</groupId><artifactId>json-path</artifactId><scope>test</scope>
</dependency><dependency><groupId>org.assertj</groupId><artifactId>assertj-core</artifactId><scope>test</scope>
</dependency><dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-core</artifactId><scope>test</scope>
</dependency><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><scope>test</scope>
</dependency>

spring-boot-starter-test includes the essential dependencies for test, such as json-path, assertj, hamcrest, mockito etc.

New annotation: @SpringBootTest

Spring Boot 1.4 introduced a new annotation @SpringBootTest to unite the old @IntegrationTest, @WebIntegrationTest, @SpringApplicationConfiguration etc, in before versions.

A webEnvironment property of @SpringBootTest is use for deciding if set up a web environment for test.

There are some configuration options of the webEnvironment.

  • MOCK is the default, provides a mock web environment.
  • NONE does not give a web environment.
  • DEFINED_PORT provides an embedded web environment and run the application on a defined port.
  • RANDOM_PORT provides an embedded web environment, but use a random port number.

If RANDOM_PORT is used, add @LocalSeverPort annotation on an int field will inject the port number at runtime.

@LocalSeverPort
int port;

@LocalServerPort replaces the @Value("${local.server.port}") of Spring Boot 1.3.

Similarly, classes property is similar to the one of @SpringApplicationConfiguration. You can specify the configuration classes to be loaded for the test.

@SpringBootTest(classes = {Application.class, SwaggerConfig.class})

The above code is equivalent to @SpringApplicationConfiguration(classes={...}) in Spring Boot 1.3.

New JUnit Runner: SpringRunner

Spring 1.4 introduced a new JUnit Runner, SpringRunner, which is an alias for the SpringJUnit4ClassRunner.

@RunWith(SpringRunner.class)

If you have to use other runners instead of SpringRunner, and want to use the Spring test context in the tests, declare a SpringClassRule and SpringMethodRule in the test to fill the gap.

@RunWith(AnotherRunner.class)
public class SomeTest{@ClassRulepublic static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();@Rulepublic final SpringMethodRule springMethodRule = new SpringMethodRule();}

Autoconfigure test slice

The most exciting feature provided in Spring Boot 1.4 is it provides capability to test some feature slice, which just pick up essential beans and configuration for the specific purpose based test.

Currently there is a series of new annotations available for this purpose.

@JsonTest provides a simple Jackson environment to test the json serialization and deserialization.

@WebMvcTest provides a mock web environment, it can specify the controller class for test and inject the MockMvc in the test.

@WebMvcTest(PostController.class)
public class PostControllerMvcTest{@Inject MockMvc mockMvc;}

@DataJpaTest will prepare an embedded database and provides basic JPA environment for the test.

@RestClientTest provides REST client environment for the test, esp the RestTemplateBuilder etc.

These annotations are not composed with SpringBootTest, they are combined with a series of AutoconfigureXXX and a @TypeExcludesFilter annotations.

Have a look at @DataJpaTest.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {}

You can add your @AutoconfigureXXX annotation to override the default config.

@AutoConfigureTestDatabase(replace=NONE)
@DataJpaTest
public class TestClass{
}

JsonComponent

@JsonComponent is a specific @Component to register custome Jackson JsonSerializer and JsonDeserializer.

For example, custom JsonSerializer and JsonDeserializer are use for serializing and deserializing LocalDateTime instance.

@JsonComponent
@Slf4j
public class LocalDateTimeJsonComponent {public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {@Overridepublic void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException {jgen.writeString(value.atZone(ZoneId.systemDefault()).toInstant().toString());}}public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {@Overridepublic LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {ObjectCodec codec = p.getCodec();JsonNode tree = codec.readTree(p);String dateTimeAsString = tree.textValue();log.debug("dateTimeString value @" + dateTimeAsString);return LocalDateTime.ofInstant(Instant.parse(dateTimeAsString), ZoneId.systemDefault());}}
}

If you are using the Spring Boot default Jackson configuration, it will be activated by default when the application starts up.

But if you customized a ObjectMapper bean in your configuration, the autoconfiguration of ObjectMapper is disabled. You have to install JsonComponentModule manually, else the @JsonComponent beans will not be scanned at all.

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder(JsonComponentModule jsonComponentModule) {Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();//....modulesToInstall(jsonComponentModule);return builder;
}

Mocking and spying Beans

Spring Boot 1.4 integrates Mockito tightly, and provides Spring specific @MockBean and @MockSpy annotations.

@RunWith(SpringRunner.class)
public class MockBeanTest {@MockBeanprivate UserRepository userRepository;}

TestConfiguration and TestComponent

TestConfiguration and TestComponent are designated for test purpose, they are similar with Configuration and Component. Generic Configuration and Component can not be scanned by default in test.

public class TestClass{@TestConfigurationstatic class TestConfig{}@TestComponentstatic class TestBean{}}

Spring 4.3

There are a few features added in 4.3, the following is impressive.

Composed annotations

The effort of Spring Composed are merged into Spring 4.3.

A series of new composed annotations are available, but the naming is a little different from Spring Composed.

For example, a RestController can be simplfied by the new annotations, list as the following table.

Spring 4.2 Spring 4.3
@RequestMapping(value = "", method = RequestMethod.GET) @GetMapping()
@RequestMapping(value = "", method = RequestMethod.POST) @PostMapping()
@RequestMapping(value = "/{id}", method = RequestMethod.PUT) @PutMapping(value = "/{id}")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @DeleteMapping(value = "/{id}")

A new @RestControllerAdvice() is provided for exception handling, it is combination of @ControllerAdvice and @ResponseBody. You can remove the @ResponseBody on the @ExceptionHandler method when use this new annotation.

For example, in the old Spring 4.2, an custom exception handler class looks like the following.

@ControllerAdvice()
public class RestExceptionHandler {@ExceptionHandler(value = {SomeException.class})@ResponseBodypublic ResponseEntity<ResponseMessage> handleGenericException(SomeException ex, WebRequest request) {}
}

In Spring 4.3, it becomes:

@RestControllerAdvice()
public class RestExceptionHandler {@ExceptionHandler(value = {SomeException.class})public ResponseEntity<ResponseMessage> handleGenericException(SomeException ex, WebRequest request) {}
}

Auto constructor injection

If there is a only one constructor defined in the bean, the arguments as dependencies will be injected by default.

Before 4.3, you have to add @Inject or @Autowired on the constructor to inject the dependencies.

@RestController
@RequestMapping(value = Constants.URI_API_PREFIX + Constants.URI_POSTS)
public class PostController {@Injectpublic PostController(BlogService blogService) {this.blogService = blogService;}
}

@Inject can be removed in Spring 4.3.

@RestController
@RequestMapping(value = Constants.URI_API_PREFIX + Constants.URI_POSTS)
public class PostController {public PostController(BlogService blogService) {this.blogService = blogService;}
}

Spring Security 4.1

The Java configuration is improved.

Before 4.1, you can configure passwordEncoder and userDetailsService via AuthenticationManagerBuilder.

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception {auth.userDetailsService(new SimpleUserDetailsServiceImpl(userRepository)).passwordEncoder(passwordEncoder);}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}}

In 4.1, userDetailsService and passwordEncoder bean can be detected automaticially. No need to wire them by AuthenticationManagerBuilder manually. No need to override the WebSecurityConfigurerAdapter class and provide a custom configuration, a generic WebSecurityConfigurerAdapter bean is enough.

@Bean
public BCryptPasswordEncoder passwordEncoder() {BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();return passwordEncoder;
}@Bean
public UserDetailsService userDetailsService(UserRepository userRepository){return new SimpleUserDetailsServiceImpl(userRepository);
}@Bean
public WebSecurityConfigurerAdapter securityConfig(){return new WebSecurityConfigurerAdapter() {@Overrideprotected void configure(HttpSecurity http) throws Exception {//...}
}

More details can be found in the What’s New in Spring Security 4.1 chapter of Spring Secuirty documentation.

Hibernate 5.2

The biggest change of Hibernate 5.2 is the packages had been reorganised, Hibernate 5.2 is Java 8 ready now.

hibernate-java8 (Java 8 DateTime support) and hibernate-entitymanager (JPA provider bridge) are merged into hibernate-core.

Remove the following dependencies when upgrade to Hibernate 5.2.

<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-java8</artifactId><version>${hibernate.version}</version>
</dependency>
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>${hibernate.version}</version>
</dependency>

NOTE:If you are using Spring 4.2 with Hibernate 5.2.0.Final, it could break some dependencis, such as spring-orm, spring-boot-data-jpa-starter which depends on hibernate-entitymanager. Spring Boot 1.4.0.RC1 and Spring 4.3 GA fixed the issues. But I noticed in the Hibernate 5.2.1.Final, hibernate-entitymanager is back.

Hibernate 5.2 also added Java Stream APIs support, I hope it will be available in the next JPA specification.

Source code

Clone the codes from Github account.

git clone https://github.com/hantsy/angularjs-springmvc-sample-boot

转载于:https://my.oschina.net/hantsy/blog/720108

Upgrade to Spring Boot 1.4相关推荐

  1. Spring Boot 2.4.5、2.3.10 发布

    前几天刚给大家介绍过Spring Framework 5.3.6的最新发布内容(Spring Framework 5.3.6.5.2.14 发布) 今天就给大家介绍Spring Boot 2.4.5 ...

  2. Spring Boot有四大神器

    序 Spring Boot有四大神器,分别是auto-configuration.starters.cli.actuator,本文主要讲actuator.actuator是spring boot提供的 ...

  3. web框架的前生今世--从servlet到spring mvc到spring boot

    背景 上世纪90年代,随着Internet和浏览器的飞速发展,基于浏览器的B/S模式随之火爆发展起来.最初,用户使用浏览器向WEB服务器发送的请求都是请求静态的资源,比如html.css等.  但是可 ...

  4. Spring Boot-Spring Tool Suit + Gradle 构建第一个Spring Boot 项目01

    文章目录 概述 使用Spring Tool Suite构建Spring Boot项目 下载STS 插件安装 搭建第一个Spring Boot项目 启动项目 概述 通常,构建一个Spring Boot项 ...

  5. spring boot 单元测试_spring-boot-plus1.2.0-RELEASE发布-快速打包-极速部署-在线演示

    spring-boot-plus spring-boot-plus 集成spring boot常用开发组件的后台快速开发脚手架 Purpose 每个人都可以独立.快速.高效地开发项目! Everyon ...

  6. java heroku_使用Spring Boot和Heroku在20分钟内完成Java的单点登录

    java heroku 建筑物身份管理,包括身份验证和授权? 尝试Stormpath! 我们的REST API和强大的Java SDK支持可以消除您的安全风险,并且可以在几分钟内实现. 注册 ,再也不 ...

  7. 使用Spring Boot和Heroku在20分钟内完成Java的单点登录

    建筑物身份管理,包括身份验证和授权? 尝试Stormpath! 我们的REST API和强大的Java SDK支持可以消除您的安全风险,并且可以在几分钟内实现. 注册 ,再也不会建立auth了! 大规 ...

  8. spring boot mybatisplus集成_spring-boot系列之集成测试

    如果希望很方便针对API进行测试,并且方便的集成到CI中验证每次的提交,那么spring boot自带的IT绝对是不二选择. 迅速编写一个测试Case @RunWith(SpringRunner.cl ...

  9. Spring Boot Initilizr - 使用ThirdParty工具

    Spring Boot Initilizr - 使用ThirdParty工具 这是我之前的两篇文章的延续.在阅读本文之前,请先阅读我之前在" Spring Boot Initilizr We ...

  10. Spring Boot(4)---入门:安装Spring Boot

    Spring Boot入门:安装Spring Boot TagsSpring Boot, Spring Boot中文官方文档 安装Spring Boot Spring Boot可以与"经典& ...

最新文章

  1. 2018-4-7 差分进化算法
  2. 一个学术 导航网站----科塔学术
  3. 13.PHP中循环结构之foreach循环语句(任务一)
  4. Java安全管理器――SecurityManager
  5. koa2使用注意点总结
  6. (加强版)大数加减乘除,一文彻底搞定
  7. 2 Oracle用户和表空间
  8. im2col原理小结
  9. python图片内容长度识别_Python实现识别图片内容的方法分析
  10. SQL Server之索引
  11. Node.js 应用故障排查手册 —— 综合性 GC 问题和优化
  12. Redis ops详解
  13. 读书笔记系列--《理解专业程序员》tips
  14. 关于数据库#1063 - Incorrect column specifier for column 'xxx'异常
  15. 如何在Python中创建常量?
  16. expect+shell脚本实现免密登录
  17. Uncaught RangeError: Maximum call stack size exceeded 超出最大调用值(个人解释)
  18. Python学习总结(九)正则表达式
  19. 【食安云桥】python 文件内批量长度除以3.5替换
  20. 如何提高软件测试效率

热门文章

  1. [Linux][Ubuntu][14.04.3LTS]安装NVidia显卡驱动
  2. 用Visual Studio写PHP代码
  3. 【Flutter】Dart中的匿名函数、闭包
  4. iOS底层探索之类的结构(上):ISA
  5. Javascript当中的RSA加解密
  6. 修改spring Boot启动时的默认图案Banner
  7. LeetCode:35. Search Insert Position(Easy)
  8. 图片加载库之Glide和Picasso对比
  9. 在web开发领域,java已死是定局。
  10. Codeforces Round #226 (Div. 2)