uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

freemarker #311

Open uniquejava opened 4 years ago

uniquejava commented 4 years ago

几百年前用过。 这次要用他来生成trigger。。

POM依赖

Spring Boot & Freemarker Configuration Example pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- or -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

FreemarkerConfig.java

Configuration

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();
    }

}

Test

@SpringBootTest
class FreemarkerWriterTest {

    @Autowired
    private FreemarkerWriter freemarkerWriter;

    @Test
    void generate() {
        Map<String, Object> data = new HashMap<>();
        data.put("id", 1);
        data.put("subject", "hello");
        data.put("message", "cyper rocks!");

        String output = null;
        try {
            output = freemarkerWriter.generate("trigger.ftl", data);
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
        System.out.println(output);

    }
}
uniquejava commented 4 years ago

模板语法

http://freemarker.foofun.cn/ref_directive_if.html