繁体   English   中英

如何从 freemarker 模板访问 spring boot 属性

[英]How to access spring boot properties from freemarker template

我的问题很简单:

在我的 spring-boot Web 应用程序中,我有一些前端/客户端需要了解的与 env 相关的属性(比方说,要调用的 CORS 远程 url 依赖于 env)。

我已经正确定义了我的 application-{ENV}.properties 文件,并且所有 per-env-props 机制都运行良好。

我似乎无法找到答案的问题是:您如何让您的 freemarker 上下文了解您的属性文件以便能够注入它们(特别是在 spring-boot 应用程序中)。 这可能很容易,但我找不到任何例子......

谢谢,

要自己回答:

spring-boot 1.3中最简单的方法是覆盖FreeMarkerConfiguration类:

/**
 * Overrides the default spring-boot configuration to allow adding shared variables to the freemarker context
 */
@Configuration
public class FreemarkerConfiguration extends FreeMarkerAutoConfiguration.FreeMarkerWebConfiguration {

    @Value("${myProp}")
    private String myProp;

    @Override
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = super.freeMarkerConfigurer();

        Map<String, Object> sharedVariables = new HashMap<>();
        sharedVariables.put("myProp", myProp);
        configurer.setFreemarkerVariables(sharedVariables);

        return configurer;
    }
}

弹簧靴2中的一个选项:

@Configuration
public class CustomFreeMarkerConfig implements BeanPostProcessor {

  @Value("${myProp}")
  private String myProp;

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName)
  throws BeansException {
      if (bean instanceof FreeMarkerConfigurer) {
          FreeMarkerConfigurer configurer = (FreeMarkerConfigurer) bean;
          Map<String, Object> sharedVariables = new HashMap<>();
          sharedVariables.put("myProp", myProp);
          configurer.setFreemarkerVariables(sharedVariables);
      }
      return bean;
  }
}

Spring Boot 2.x更改了类结构,因此不再可能使用Spring Boot 1.x进行子类化并保持自动配置。

import freemarker.template.Configuration;

@Component
public class FreemarkerConfiguration {

    @Autowired
    private Configuration freemarkerConfig;

    @Value("${myProp}")
    private String myProp;

    Map<String, Object> model = new HashMap();
    model.put("myProperty", myProp);
  

    // set loading location to src/main/resources
    freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/");
    Template template = freemarkerConfig.getTemplate("template.ftl");
    String templateText = FreeMarkerTemplateUtils.
                                    processTemplateIntoString(template, model);

}   


     
  step 2, 
   get property in freemarker template code.
     <div>${myProperty}</td>
   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM