【问题标题】:use property value in thymeleaf th:if condition在 thymeleaf th:if 条件中使用属性值
【发布时间】:2017-10-23 09:35:21
【问题描述】:

基本上我在属性文件中有配置

data.enabled = true

我为此添加了一个 POJO 类

@Configuration
@PropertySource(value = {"classpath:dataconfig.properties"})
public class DataProperties {
    private Boolean enabled;
}

我想使用 thymeleaf 检查 html 标签上的 enabled 属性。

<li th:if="${DataProperties.getEnabled() == true}"><h3>Hello</h3></li>

【问题讨论】:

  • 错误是什么?
  • 我正在启用属性 null
  • 请显示您的控制器代码...或者至少您如何填充模型。

标签: spring-boot thymeleaf


【解决方案1】:

首先您应该将@ConfigurationProperties(prefix="data") 添加到您的配置类中。

@Configuration
@PropertySource("classpath:dataconfig.properties")
@ConfigurationProperties(prefix="data")
public class DataProperties {
    private Boolean enabled;

这会激活您的变量直接绑定到属性值而不使用@Value 注释。在您的属性文件中,您有data.enabled。这意味着您的前缀是data。所以你也必须设置它。

要直接使用 thymeleaf 中的 bean,您需要使用特殊命令。在您的情况下,它应该如下所示:(see point 5 in the docs)

<li th:if="${@dataProperties.getEnabled() == true}" ><h3>Hello</h3></li>

加法1:

要在控制器等其他 Spring bean 中使用相同的属性,您必须自动连接您的 DataProperties

@Controller
public class IndexController {

    @Autowired
    private DataProperties dataProperties;

    @GetMapping("/")
    public String index() {
        dataProperties.getEnabled();
        return "index";
    }

只是提到它在字段上自动装配是不好的做法。但您可以选择像这样使用它或在构造函数或设置器上自动装配。

【讨论】:

  • 我如何在控制器中使用相同的属性??
猜你喜欢
  • 1970-01-01
  • 2017-07-01
  • 2014-08-29
  • 2013-04-07
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
相关资源
最近更新 更多