一、集成Log4j2⽇志框架
从Spring5之后,Spring框架⽀持集成的⽇志框架是Log4j2.如何启⽤⽇志框架:
第⼀步:引⼊Log4j2的依赖
<!--log4j2的依赖--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.19.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j2-impl</artifactId> <version>2.19.0</version> </dependency>
第⼆步:在类的根路径下提供log4j2.xml配置⽂件(⽂件名固定为:log4j2.xml,⽂件必须放到类根路径 下。)
<?xml version="1.0" encoding="UTF-8"?> <configuration> <loggers> <!-- level指定⽇志级别,从低到⾼的优先级: ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF --> <root level="DEBUG"> <appender-ref ref="spring6log"/> </root> </loggers> <appenders> <!--输出⽇志信息到控制台--> <console name="spring6log" target="SYSTEM_OUT"> <!--控制⽇志输出的格式--> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [%t] %-3le vel %logger{1024} - %msg%n"/> </console> </appenders> </configuration>
第三步:使⽤⽇志框架
Logger logger = LoggerFactory.getLogger(FirstSpringTest.class); logger.info("我是⼀条⽇志消息");
二、Spring对JUnit4的⽀持
依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
单元测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring.xml") public class SpringJUnit4Test { @Autowired private User user; @Test public void testUser(){ System.out.println(user.getName()); } }
Spring提供的⽅便主要是这⼏个注解:
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration("classpath:spring.xml")
在单元测试类上使⽤这两个注解之后,在单元测试类中的属性上可以使⽤@Autowired。⽐较⽅便。
三、Spring对JUnit5的⽀持
引⼊JUnit5的依赖,Spring对JUnit⽀持的依赖还是:spring-test,如下
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.9.0</version> <scope>test</scope> </dependency>
单元测试
@ExtendWith(SpringExtension.class) @ContextConfiguration("classpath:spring.xml") public class SpringJUnit5Test { @Autowired private User user; @Test public void testUser(){ System.out.println(user.getName()); } }
在JUnit5当中,可以使⽤Spring提供的以下两个注解,标注到单元测试类上,这样在类当中就可以使⽤ @Autowired注解了。
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:spring.xml")