对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

使用 @Value

@Value 通常用于注入外部属性:spring-doc.cadn.net.cn

@Component
public class MovieRecommender {

    private final String catalog;

    public MovieRecommender(@Value("${catalog.name}") String catalog) {
        this.catalog = catalog;
    }
}
@Component
class MovieRecommender(@Value("\${catalog.name}") private val catalog: String)

使用以下配置:spring-doc.cadn.net.cn

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig { }
@Configuration
@PropertySource("classpath:application.properties")
class AppConfig

以及以下 application.properties 个文件:spring-doc.cadn.net.cn

catalog.name=MovieCatalog

在这种情况下,catalog参数和字段将等于MovieCatalog的值。spring-doc.cadn.net.cn

Spring 提供了一个默认的宽松嵌入式值解析器。它会尝试解析属性值,如果无法解析,则会将属性名称(例如 ${catalog.name})作为值注入。如果您希望对不存在的值保持严格的控制,应该声明一个 PropertySourcesPlaceholderConfigurer bean,如下例所示:spring-doc.cadn.net.cn

@Configuration
public class AppConfig {

	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}
}
@Configuration
class AppConfig {

	@Bean
	fun propertyPlaceholderConfigurer() = PropertySourcesPlaceholderConfigurer()
}
在使用 JavaConfig 配置 PropertySourcesPlaceholderConfigurer 时,@Bean 方法必须为 static

使用上述配置可以在任何 ${} 占位符无法解析时确保 Spring 初始化失败。也可以使用方法如 setPlaceholderPrefixsetPlaceholderSuffixsetValueSeparator 来自定义占位符。spring-doc.cadn.net.cn

Spring Boot 默认配置了一个 PropertySourcesPlaceholderConfigurer bean,它将从 application.propertiesapplication.yml 文件中获取属性。

Spring 提供的内置转换器支持允许简单的类型转换(例如转换为 Integerint)自动处理。多个逗号分隔的值可以自动转换为 String 数组而无需额外努力。spring-doc.cadn.net.cn

可以如下方式提供默认值:spring-doc.cadn.net.cn

@Component
public class MovieRecommender {

    private final String catalog;

    public MovieRecommender(@Value("${catalog.name:defaultCatalog}") String catalog) {
        this.catalog = catalog;
    }
}
@Component
class MovieRecommender(@Value("\${catalog.name:defaultCatalog}") private val catalog: String)

Spring BeanPostProcessor 在后台使用 ConversionService 来处理将 String 值在 @Value 中转换为目标类型的流程。如果您想为自己的自定义类型提供转换支持,可以如下面的示例所示提供您自己的 ConversionService bean 实例:spring-doc.cadn.net.cn

@Configuration
public class AppConfig {

    @Bean
    public ConversionService conversionService() {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
        conversionService.addConverter(new MyCustomConverter());
        return conversionService;
    }
}
@Configuration
class AppConfig {

	@Bean
	fun conversionService(): ConversionService {
		return DefaultFormattingConversionService().apply {
			addConverter(MyCustomConverter())
		}
	}
}

@Value 包含一个 SpEL 表达式 时,该值将在运行时动态计算,如下例所示:spring-doc.cadn.net.cn

@Component
public class MovieRecommender {

    private final String catalog;

    public MovieRecommender(@Value("#{systemProperties['user.catalog'] + 'Catalog' }") String catalog) {
        this.catalog = catalog;
    }
}
@Component
class MovieRecommender(
	@Value("#{systemProperties['user.catalog'] + 'Catalog' }") private val catalog: String)

SpEL 还支持使用更复杂的数据结构:spring-doc.cadn.net.cn

@Component
public class MovieRecommender {

    private final Map<String, Integer> countOfMoviesPerCatalog;

    public MovieRecommender(
            @Value("#{{'Thriller': 100, 'Comedy': 300}}") Map<String, Integer> countOfMoviesPerCatalog) {
        this.countOfMoviesPerCatalog = countOfMoviesPerCatalog;
    }
}
@Component
class MovieRecommender(
	@Value("#{{'Thriller': 100, 'Comedy': 300}}") private val countOfMoviesPerCatalog: Map<String, Int>)