【问题标题】:Why @Value works differently in Spring Core & Spring Boot?为什么 @Value 在 Spring Core 和 Spring Boot 中的工作方式不同?
【发布时间】:2021-10-14 02:58:59
【问题描述】:

我有一个简单的Spring Core 项目,我正在从src/main/resources/application.properties 文件中读取一些值。

Team.java

@Setter
@Getter
@ToString
@Component
@PropertySource("classpath:application.properties")
public class Test {
    @Value("${teamName}")
    private String teamName;
    @Value("${players}")
    private List<String> players;
}

App.java

@ComponentScan
public class App {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(App.class);
        Team team = applicationContext.getBean(Team.class);
        System.out.println(team.getTeamName());
        System.out.println(team.getPlayers() + "   " + team.getPlayers().size());
    }
}

application.properties

teamName=Avengers
players=Iron Man,Captain America,Thor,Hulk

输出

Avengers
[Iron Man,Captain America,Thor,Hulk]   1

teamName 读取完美,但当涉及到players 时,它会将所有玩家值读取为单个字符串。理想情况下,玩家大小应该是4,但得到了1。当我将 @Value("${players}") 更改为 @Value("#{'${players}'.split(',')}") 时,它按预期工作。意味着我正在获取玩家大小4

现在的问题是,在Spring Boot@Value("${players}") 中使用相同的代码给我的玩家大小为4,但在正常的Spring core 项目中给我1。那么它背后的原因是什么,你能给我一个应该在 Spring 核心项目中工作的解决方案吗?我的意思是如何处理@Value("${players}"),以便我可以将玩家尺寸设为4

【问题讨论】:

  • 嗨@Tom,我已经阅读了该文档,然后我发布了这个问题。我已经在问题中提到,当我使用 @Value("#{'${players}'.split(',')}") 时,会按照我仅从该文档中获得帮助的期望工作。但是当我使用@Value("${players}") 时,它不能按预期工作。但同样的事情,即@Value("${players}") in Spring Boot 给了我玩家大小4。为什么?
  • 我链接的那个答案不使用SpEL。

标签: java spring spring-boot properties spring-annotations


【解决方案1】:

Spring Boot 和非Spring Boot 应用程序如果不使用 默认值 可能会有不同的行为,因为 Spring Boot em> 使用一组不同的配置和引导工具,因此需要它。

其中一种配置差异是注入了基本的org.springframework.core.convert.ConversionService 实现org.springframework.boot.context.properties.bind.BindConverter.TypeConverterConversionService,它允许对简单类型进行基于属性的转换:基元、数组、集合...

为了适应非Spring Boot 应用程序的行为,您需要自己注入一个org.springframework.core.convert.ConversionService 实现。如果您使用的是基于 Java 的配置,则可以注入通常适用于大多数情况的 org.springframework.core.convert.support.GenericConversionService

import org.springframework.core.convert.support.GenericConversionService;

@Configuration
public class MyConfiguration {

    @Bean
    public ConversionService conversionService() {
        return new GenericConversionService();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2021-09-28
    • 2018-12-29
    • 2023-04-02
    • 2015-01-18
    • 2016-09-03
    相关资源
    最近更新 更多