Skip to content

freemarker #311

Description

@uniquejava

几百年前用过。 这次要用他来生成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);

    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions