我有一个简单的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
的球员尺寸?
Spring Boot和非Spring Boot应用程序在使用默认值时可能表现不同因为Spring Boot使用了一组不同的配置和引导工具,因此需要它。
这种配置的区别之一是注入了一个基本的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();
}
}