Hand tear Spring5 framework (11) Spring5 new features

JDK 8+ and Java EE7+ and above

  • The code of the entire framework is based on java8

  • Improve readability by using features such as generics

  • Improve direct code support for java8

  • Compatible with JDK9 at runtime

  • Java EE 7 API requires Spring related module support

  • Compatible with Java EE8 API at runtime

  • Cancelled packages, classes and methods

  • 包 beans.factory.access

  • 包 dbc.support.nativejdbc

  • Removed package mock.staicmock from spring-aspects module, no longer mentioning AnnotationDrivenStaticEntityMockingControl support

  • Many deprecated classes and methods are removed from the code base

Core features

JDK8 enhancements:

  • Provides getFile or isFile defensive abstraction when accessing Resuouce

  • Effective method parameter access based on Java 8 reflection enhancement

  • Added support for declaring the default method in the Spring core interface, always using JDK7 Charset and StandardCharsets enhancement

  • Compatible with JDK9

  • Spring 5.0 framework comes with a common log package

  • Continuously instantiate the via constructor (modified exception handling)

  • Spring 5.0 framework comes with a common log package

  • spring-jcl replaces the general log and still supports rewritable

  • Automatically detect log4j 2.x, SLF4J, JUL (java.util.Logging) instead of other support

  • Provides getFile or isFile defensive abstraction when accessing Resuouce

  • NIO-based readableChannel also provides this new feature

Core container

  • Support candidate component index (can also support environment variable scanning)

  • Support @Nullable annotation

  • Functional style GenericApplicationContext/AnnotationConfigApplicationContext

  • Basic support for bean API registration

  • When using CGLIB dynamic proxy at the interface level, it provides transaction, cache, and asynchronous annotation detection

  • XML configuration scope stream

  • Spring WebMVC

  • All Servlet 3.1 signature support is implemented in Spring-provied Filter

  • Support Servlet4.0 PushBuilder parameter in Spring MVC Controller method

  • Data binding of multiple immutable objects (Kotlin/Lombok/@ConstructorPorties)

  • Support jackson2.9

  • Support JSON binding API

  • Support protobuf3

  • Support Reactor3.1 Flux and Mono

Integrated logging framework

spring5 integrates log4j2 logging tool

First of all, we still use the project created in transaction management, which is the example of transfer, to add the function of recording logs.

The first step is to introduce related dependencies

<!-- log4j2日志相关jar包引用-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.2</version>
        </dependency>

        <!--用于slf4j与log4j2保持桥接 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.11.2</version>
        </dependency>

The second step is to create the log4j2.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!--
       日志输出级别,共有8个级别,按照从低到高为:All < Trace < Debug < Info < Warn < Error < Fatal < OFF.
-->
<Configuration status="warn">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

The third step is to create a Logger object and enter log information.

package org.learn.spring5.service.impl;

import org.learn.spring5.dao.UserDao;
import org.learn.spring5.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {

    private static final Logger log= LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Autowired
    private UserDao userDao;
    public void transferAccount() {
        log.info("执行了 transferAccount 方法");
        //小明转账100,减少100元
        userDao.reduceMoney();
        int i = 10/0;
        //小红账户增加100元
        userDao.addMoney();
    }
}

Execute test program

import org.junit.Test;
import org.learn.spring5.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {


    /**
     * Spring5整合log4j2
     */
    @Test
    public void testAccount() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.transferAccount();//转账操作
    }

}

Return result

19:05:51.899 [main] INFO  com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
19:05:52.254 [main] INFO  org.learn.spring5.service.impl.UserServiceImpl - 执行了 transferAccount 方法

The results showed that our log information was successfully output according to the format set by the log4j2 configuration file, and the log4j2 framework was successfully integrated.

Nullable annotations and functional style programming

@NonNull

Used in fields, method parameters, or method return values. Indicates that it cannot be empty

@NonNullFields

Used at the package level, and the field of the class under the package cannot be empty.

When too many NonNull fields are used in a class, you can consider using @NonNullFields annotation. To use this annotation, you must first define a package-info.javafile named , for example:

package-info.java

 

@NonNullApi
@NonNullFields
package org.springframework.mail;

import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

@Nullable

Used in fields, method parameters, or method return values. Indicates that it can be empty.

When a class is wrapped @NonNullFieldsor @NonNullApiannotated, and we want to exempt certain fields, methods, and return values ​​from the non-null constraints specified at the package level, we can use@Nullable

@NonNullApi

The @NonNullFieldssame as used at the package level, but the difference is that its function is that the method parameters and return values ​​of the classes under the package cannot be empty

When the method parameters and return value in a class use too many NonNull, you can consider using the @NonNullFields annotation. To use this annotation, you must first define a package-info.javafile named with the same form as above.

  • Functional style programming

Create objects in a functional style and hand them over to Spring for management

1. Create a GenericApplicationContext object

2. Call the registerBean method of context to register the object

3. Get objects registered in Srping

@Test
    public void test2() {
        //1.手动实例化对象
        User user = new User();
        //2.创建GenericApplicationContext对象
        GenericApplicationContext context = new GenericApplicationContext();
        context.refresh();
        //3.调用context的registerBean方法注册对象
        context.registerBean("user1", User.class, () -> new User());
        User bean = (User) context.getBean("user1");
        System.out.println(bean);

    }

Integrate JUnit5 unit testing framework

The first step is to introduce related dependencies

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
			<!-- junit5 -->
  		<dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

The second step is to create a test class and add junit5 annotations

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.learn.spring5.service.UserService;
import org.learn.spring5.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class TestSpring5 {

    @Autowired
    private UserService userService;
    /**
     * Spring5整合junit5
     */
    @Test
    public void testAccount() {
        userService.transferAccount();//转账操作
    }


}

 

Guess you like

Origin blog.csdn.net/java_cxrs/article/details/108632500