簡體   English   中英

無法使用注釋從.properties文件中提取值

[英]Can't pull values from .properties file using annotations

我想通過.proprerties文件配置我的bean字符串字段。 但它不會取代值鍵,意味着它回顯“$ {value}”字符串。 我的代碼如下:

主要課程:

public class Main {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        ValuesContainer valuesContainer = (ValuesContainer) applicationContext.getBean("container");
        System.out.println(valuesContainer.getValue()); //echoes "${value}" instead of Ho-ho-ho!
    }
}

應用背景:

.....
<context:annotation-config />
<context:component-scan base-package="bean"/>

豆:

package bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("container")
@Scope("singleton")
@PropertySource(value = "classpath:app.properties")
public class ValuesContainer {

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

    public String getValue() {
        return value;
    }
}

app.properties:

value = Ho-ho-ho!

看起來您在配置中缺少PropertySourcesPlaceholderConfigurer。

這篇文章

@PropertySource應與@Configuration一起使用。

您需要創建一個單獨的@Configuration類,將注釋@PropertySource放在其上並將其添加到您的應用程序上下文中(或者讓<context:component-scan>添加它)。

或者,您可以使用Environment編程方式配置應用程序上下文的屬性源。

暫無
暫無

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

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