001package io.jstach.opt.spring; 002 003import java.util.List; 004import java.util.ServiceLoader; 005 006import org.eclipse.jdt.annotation.Nullable; 007import org.springframework.core.env.Environment; 008import org.springframework.core.env.PropertyResolver; 009 010import io.jstach.jstachio.Template; 011import io.jstach.jstachio.spi.JStachioConfig; 012import io.jstach.jstachio.spi.JStachioExtensionProvider; 013import io.jstach.jstachio.spi.JStachioTemplateFinder; 014 015/** 016 * JStachio services based on Spring notably the {@linkplain #provideConfig() config} and 017 * {@linkplain #provideTemplateFinder() template finding}. 018 * 019 * @apiNote Although this is an extension it is not designed to be loaded by the 020 * {@link ServiceLoader}. 021 * @author agentgt 022 * 023 */ 024public class SpringJStachioExtension implements JStachioExtensionProvider { 025 026 private final JStachioConfig config; 027 028 private final JStachioTemplateFinder templateFinder; 029 030 /** 031 * Constructor for injection 032 * @param config jstachio config see {@link #config(PropertyResolver)} 033 * @param templateFinder template finder to use 034 */ 035 public SpringJStachioExtension(JStachioConfig config, JStachioTemplateFinder templateFinder) { 036 super(); 037 this.config = config; 038 this.templateFinder = templateFinder; 039 } 040 041 /** 042 * Creates a JStachio config from a property resolver (usually {@link Environment}). 043 * @param propertyResolver wrapper property resolver 044 * @return config 045 */ 046 public static JStachioConfig config(@SuppressWarnings("exports") PropertyResolver propertyResolver) { 047 return new SpringJStachioConfig(propertyResolver); 048 } 049 050 /** 051 * Constructor for injection 052 * @param environment springs environment to be used for {@link JStachioConfig} 053 * @param templates templates found via spring 054 */ 055 public SpringJStachioExtension(@SuppressWarnings("exports") Environment environment, List<Template<?>> templates) { 056 this(config(environment), 057 JStachioTemplateFinder.cachedTemplateFinder(JStachioTemplateFinder.of(templates, -1))); 058 } 059 060 /** 061 * {@inheritDoc} The config comes from Spring {@link Environment} abstraction. 062 */ 063 @Override 064 public JStachioConfig provideConfig() { 065 return this.config; 066 } 067 068 /** 069 * {@inheritDoc} The provided template finder instead of using reflection delegates to 070 * the templates wired in via spring. 071 */ 072 @Override 073 public JStachioTemplateFinder provideTemplateFinder() { 074 return this.templateFinder; 075 } 076 077 private static final class SpringJStachioConfig implements JStachioConfig { 078 079 private final PropertyResolver propertyResolver; 080 081 SpringJStachioConfig(PropertyResolver propertyResolver) { 082 super(); 083 this.propertyResolver = propertyResolver; 084 } 085 086 @Override 087 public @Nullable String getProperty(String key) { 088 return propertyResolver.getProperty(key); 089 } 090 091 } 092 093}