簡體   English   中英

從messages.properties訪問application.properties

[英]Access application.properties from messages.properties

我需要從messages.properties中的application.properties訪問屬性:

application.properties

max-size=3

messages.properties

alert.error=You can only save {max-size} items.

無法運作:

{max-size}, #{max-size}, ${max-size}

我知道這個線程,但是我需要任何Java文件之外的線程。

更新: maven方法在application.properties文件中有效,但在application.properties和messages.properties之間無效。 不應該下訂單嗎? 如果文件A具有密鑰a,但是首先解析文件B時,a在B中尚不可用,是嗎?

我的pom.xml中的代碼段:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                </includes>
            </resource>

“#{alert.error($ {@ environment.getProperty( '最大規模')})}”

您可以使用構建工具(Maven / Gradle / ...)替換它,也可以在消息中使用參數,如下所示:

alert.error=You can only save {0} items.

現在,您可以自動連接MessageSource並檢索您的maxSize

@Autowired
private MessageSource messageSource;
@Value("${max-size}")
private int maxSize;

然后您可以通過以下方式使用它:

messageSource.getMessage("alert.error", new Object[]{maxSize}, locale);

通過此解決方案,您還可以將消息用於其他大小,而不僅僅是將其設置為3。

如果您想在視圖中使用它(例如,與Thymeleaf一起使用),則可以執行以下操作:

<p th:text="#{alert.error(${@environment.getProperty('max-size')})}"></p>

如果要在Maven中進行構建,則可以在構建時過濾message.properties。

https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

您可以通過調用資源插件目標https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html通過maven進行操作

messages.properties放在src / main / resources中

<build>
        <filters>
            <filter>src/main/resources/application.properties</filter>
        </filters>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

調用mvn resources:resources

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM