Spring框架基于Jdk8,兼容Jdk9。介绍一下Spring5的新功能:
1.支持整合日志框架
Spring5自带通用的日志封装,也可以对其他日志框架进行整合。Spring5移除Log4jConfigListener(对log2j整合),不支持log4j,官方建议使用log4j2。
(1)相关jar包:
(2)log4j2.xml
(该配置文件名字固定为log4j2.xml
,否则无法识别)
<?xml version="1.0" encoding="UTF-8" ?>
<!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,可以看到Iog4j2内部各种详细输出-->
<configuration status="INFO">
<!--定义所有的appender-->
<appenders>
<!-- 日志输出到控制台 -->
<Console name="Console" target="SYSTEM_OUT">
<!--日志级别以及优先级排序:OFF 〉FATAL 〉ERROR 〉WARN 〉INFO 〉DEBUG 〉TRACE > ALL-->
<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</appenders>
<loggers>
<root level="INFO">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
方式1:直接调用方法
方式2:手动输出
2.支持@Nullable注解
Spring和核心容器支持@Nullable
注解
① 使用在方法:方法返回可以为空;
② 属性:属性值可以为空;
③ 方法参数:参数值可以为空。
3.支持函数式风格GenericApplicationContext
public class User {}
//函数式风格GenericApplicationContext测试类
public class GenericApplicationContextTest {
//函数式风格创建对象,交给Spring管理
@Test
public void GenericApplicationContextTest(){
//1.创建GenericApplicationContext对象
GenericApplicationContext context = new GenericApplicationContext();
//2.调用context的方法完成对象注册
context.refresh();
context.registerBean("user", User.class,()->new User());//函数式风格创建对象
//3.获取注册的对象
User user = (User) context.getBean("user");
System.out.println(user);
}
}
5.支持整合JUnit5单元测试框架
(1)Spring整合JUnit4
① 引入jar包:spring-test-5.2.6.RELEASE.jar
,添加JUnit4依赖:
② 创建测试类,使用JUnit4注解测试:
//此处使用的注解是JUnit4中的注解
@RunWith(SpringJUnit4ClassRunner.class)//单元测试框架
@ContextConfiguration("classpath:applicationContext-annotation.xml")//加载配置文件
public class Junit4Test {
@Autowired
private AccountDao accountDao;
@Test
public void test1(){
accountDao.transfer("张无忌","赵敏",200);
System.out.println("转账完成...");
}
}
(5)Spring整合JUnit5
① 添加JUnit5依赖
② 创建测试类,使用JUnit5注解测试:
//此处使用的注解是JUnit5中的注解
@ExtendWith(SpringExtension.class)//单元测试框架
@ContextConfiguration("classpath:applicationContext-annotation.xml")//加载配置文件
//@SpringJUnitConfig(locations = "classpath:applicationContext-annotation.xml")//符合注解实现(等价于上面两个注解)
public class Junit5Test {
@Autowired
private AccountDao accountDao;
@Test
public void test1(){
accountDao.transfer("张无忌","赵敏",200);
System.out.println("转账完成...");
}
}