SpringBoot 配置 FreeMarkderConfig
时间: 2024-03-12 18:47:45 浏览: 12
在 Spring Boot 中,配置 FreeMarkerConfig 非常简单,只需要按照以下步骤进行操作即可:
1. 在 pom.xml 文件中添加 FreeMarker 的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
```
2. 创建 FreeMarkerConfig 的 Java 配置类:
```java
@Configuration
public class FreeMarkerConfig {
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("classpath:/templates/");
configurer.setDefaultEncoding("UTF-8");
return configurer;
}
}
```
以上代码中,我们通过 @Configuration 注解将 FreeMarkerConfig 类声明为一个配置类,通过 @Bean 注解创建 FreeMarkerConfigurer 实例,并设置模板所在的路径和编码方式。
3. 在 application.properties 或 application.yml 文件中配置 FreeMarker 的相关属性:
```properties
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.charset=UTF-8
```
以上代码中,我们通过 spring.freemarker.prefix 属性指定模板所在的路径,通过 spring.freemarker.charset 属性指定编码方式。
通过以上步骤,我们就可以成功地配置 FreeMarker 模板引擎了。在 Spring Boot 中,我们可以直接使用 FreeMarker 模板引擎来渲染视图,无需进行额外的配置。