错误提示
java.lang.NoClassDefFoundError: ognl/PropertyAccessor
解决方法
在 pom 文件中添加如下依赖:
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.26</version>
</dependency>
错误重现
出现错误的代码:
public class Tests {
@Test
public void test0() {
TemplateEngine templateEngine = new TemplateEngine();
String input = "<p th:text='${age}'></p>";
Context context = new Context();
context.setVariable("age", "3");
String output = templateEngine.process(input, context);
System.out.println(output);
}
}
pom 文件:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
错误原因
在 org.thymeleaf:thymeleaf-spring5 的 pom 文件中,排除了 ognl:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.15.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
</exclusion>
</exclusions>
</dependency>
依赖关系如下图:

对比一下正常的 org.thymeleaf:thymeleaf 的依赖关系:
