gpt4 book ai didi

java - Spring @Value 没有解析为属性文件中的值

转载 作者:IT老高 更新时间:2023-10-28 13:02:41 29 4
gpt4 key购买 nike

我以前在其他项目中也有过这个工作,我只是重新做同样的事情,但由于某种原因它不起作用。 Spring @Value 不是从属性文件中读取,而是从字面上获取值

AppConfig.java

@Component
public class AppConfig
{
@Value("${key.value1}")
private String value;

public String getValue()
{
return value;
}
}

applicationContext.xml:

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

<bean id="appConfigProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:appconfig.properties" />
</bean>

appconfig.properties

key.value1=test value 1

在我的 Controller 中,我有:

@Autowired
private AppConfig appConfig;

应用程序启动得很好,但是当我启动时

appConfig.getValue()

返回

${key.value1}

它不会解析为属性文件中的值。

想法?

最佳答案

我还发现 @value 不起作用的原因是,@value 需要 PropertySourcesPlaceholderConfigurer 而不是 PropertyPlaceholderConfigurer。我做了同样的改变,它对我有用,我使用的是 spring 4.0.3 版本。我在配置文件中使用以下代码进行了配置 -

@Bean 
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

关于java - Spring @Value 没有解析为属性文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15937592/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com