Access application.properties value in thymeleaf template

这一生的挚爱 提交于 2020-12-04 18:42:00

问题


I have one of my spring boot application and inside my application.properties there is one of the property is url=myurl.net. In the same application I have one thyme leaf html template. I wanted to get the url value into that template. I am using the following code inside the thymeleaf html template <font face=arial size=2 > access the url : </font> ${environment.getProperty(‘url’)}

Output I am getting :

access the url : $(environment.getProperty(‘url’)}

Output I am expecting:

access the url : myurl.net

Instead of actual value I am getting the same text. Can someone please help me on this. Appreciate your help.


回答1:


You have to use

${@environment.getProperty('css.specific.name')} this will fetch css.specific.name property from the application.properties file.




回答2:


Map your prop value in your controller, and call it directly from Thymeleaf template.

@Controller
public class XController {

    @Value("${pcn.app.url}")
    private String url;     // Directly instead of using envireonment

    @RequestMapping(value = "form-show", method = RequestMethod.GET)
    public ModelAndView showForm() {
        ModelAndView model = new ModelAndView();
        model.setViewName("your-view");

        // The key which will look in your HTML with.
        model.addObject("urlValue", url);
        return model;
    }
}

In your html normally call it like this

<html>
    <body>
        <span th:text="#{urlValue}"></span>
    </body>
</html>



回答3:


Alternatively you define settings as data strucutres, and access them through bean scopes

application.properties

foo.bar=something

Foo.java

@Configuration
@EnableConfigurationProperties(Foo.class)
@ConfigurationProperties("foo")
public class Foo {
  private String bar;

  public void setBar(String bar) { this.bar = bar; }
  public String getBar() { return bar; }
}

sometemplate.html

...
<span th:text="@foo.getBar()"></span>
...



回答4:


I am using like below

@Service("mapService")
public class MapService {

    @Value("${maps.google.api.key}")
    private String googleMapApiKey;

    @RequestMapping(value = "/google/key", method = RequestMethod.GET)
    public String getGoogleMapApiKey() {
        return googleMapApiKey;
    }
}


<script th:src="@{'https://maps.googleapis.com/maps/api/js?'+'key='+${@mapService.getGoogleMapApiKey()}+'&libraries=places&callback=initAutocomplete'}"></script>


来源:https://stackoverflow.com/questions/56102116/access-application-properties-value-in-thymeleaf-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!