import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
@Configuration
public class FreemarkerConfig {
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() throws Exception {
FreeMarkerConfigurer fmc = new FreeMarkerConfigurer();
fmc.setTemplateLoaderPath("classpath:/freemarker");
fmc.setDefaultEncoding("UTF-8");
return fmc;
}
}
模板 ftl
src/main/resources/freemarker/niubi.ftl
<#assign triggerName = "trigger_${id}">
drop trigger if exists ${triggerName}
create trigger ${triggerName}
after update
on customer
for each row
begin
if old.grade <> new.grade THEN
...
end if;
end;
Service/Utils
@Component
public class FreemarkerWriter {
@Autowired
private FreeMarkerConfigurer configurer;
public String generate(String templateName, Object data) throws Exception {
Template template = configurer.getConfiguration().getTemplate(templateName);
StringWriter writer = new StringWriter();
template.process(data, writer);
return writer.getBuffer().toString();
}
}
几百年前用过。 这次要用他来生成trigger。。
POM依赖
Spring Boot & Freemarker Configuration Example pom.xml
FreemarkerConfig.java
Configuration
模板 ftl
src/main/resources/freemarker/niubi.ftl
Service/Utils
Test