Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

freemarker #311

Open
uniquejava opened this issue May 7, 2020 · 1 comment
Open

freemarker #311

uniquejava opened this issue May 7, 2020 · 1 comment

Comments

@uniquejava
Copy link
Owner

uniquejava commented May 7, 2020

几百年前用过。 这次要用他来生成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
Copy link
Owner Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant