繁体   English   中英

在Spring Expression Language中访问属性文件

[英]Accessing properties file in Spring Expression Language

我用Thymeleaf使用Spring Boot创建了一个简单的Web应用程序。 我使用application.properties文件作为配置。 我想要做的是向该文件添加名称和版本等新属性,并访问Thymeleaf的值。

我已经能够通过创建一个新的JavaConfiguration类并暴露一个Spring Bean来实现这一点:

@Configuration
public class ApplicationConfiguration {

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

    @Bean
    public String name() {
        return name;
    }

}

我可以使用Thymeleaf在模板中显示它,如下所示:

<span th:text="${@name}"></span>

这对我来说似乎过于冗长和复杂。 实现这一目标的更优雅方式是什么?

如果可能的话,我想避免使用xml配置。

你可以通过Environment获得它。 例如:

${@environment.getProperty('name')}

在JavaConfig中执行此操作非常简单。 这是一个例子:

@Configuration
@PropertySource("classpath:my.properties")
public class JavaConfigClass{

    @Value("${propertyName}")
    String name;


    @Bean //This is required to be able to access the property file parameters
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
}

或者,这是XML等价物:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
         <value>my.properties</value>
    </property>
</bean>

最后,您可以使用Environment变量,但无缘无故需要额外的代码。

暂无
暂无

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

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