Spring框架新功能
日志、单元测试
-
整个Spring5框架基于java8,运行时兼容java9,许多不建议使用的类和方法在代码库中删除
-
Spring5框架自带了通用的日志封装
- Spring5已经移除Log4jConfigListener,官方建议使用Log4j2
- Spring5框架整合Log4j2
步骤
-
引入jar包
-
创建log4j2.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,可以看到log4j2内部各种详细输出--> <configuration status="INFO"> <!--先定义所有的appender--> <appenders> <!--输出日志信息到控制台--> <console name="Console" target="SYSTEM_OUT"> <!--控制日志输出的格式--> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </console> </appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效--> <!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出--> <loggers> <root level="info"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
-
Spring5框架核心容器支持@Nullable注解
-
@Nullable注解可以使用在方法上面,属性上面,参数上面,表示方法返回可以为空,属性值可以为空,参数值可以为空
-
注解用在方法上面,方法返回值可以为空
-
注解用在参数上面,表示参数可以为空
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wHZ0Vcio-1649666660262)(Spring概述.assets/image-20220411160620269.png)]
-
注解方法用在属性上面,表示属性值可以为空
-
-
Spring5核心容器支持函数式风格GenericApplicationContext
-
函数风格创建对象,交给Spring进行管理
@Test public void testGenerucApplicationContext(){ //创建GenerucApplicationContext对象 GenericApplicationContext genericApplicationContext = new GenericApplicationContext(); //调用genericApplicationContext方法的对象注册 genericApplicationContext.refresh(); genericApplicationContext.registerBean("User1",User.class,() -> new User()); //获取在Spring注册的对象 //User user = (User) genericApplicationContext.getBean("com.cwy.day04.User");//这里通过路径找对象 User user = (User) genericApplicationContext.getBean("User1"); System.out.println(user); }
-
-
Spring5支持整合JUnit5
-
整合JUnit4
-
引入Spring相关针对测试依赖 spring-test-5.2.6.RELEASE.jar
-
创建测试类,使用注解方式完成
@RunWith(SpringJUnit4ClassRunner.class)//指定单元测试框架 @ContextConfiguration("classpath:beans3.xml") //加载配置文件 public class JTest4 { @Autowired private UserService userService; @Test public void test1(){ userService.accountMoney(); } }
-
-
整个JUnit5
-
引入相关jar包
-
创建测试类,使用注解方式完成
@ExtendWith(SpringExtension.class) @ContextConfiguration("classpath:beans3.xml") //加载配置文件 public class JTest5 { @Autowired private UserService userService; @Test public void test1(){ userService.accountMoney(); } }
-
使用一个复合注解替代上面两个注解完成整合
@SpringJUnitConfig(locations = "classpath:beans3.xml") public class JTest5 { @Autowired private UserService userService; @Test public void test1(){ userService.accountMoney(); } }
-
-