Spring @Value 注解的使用与理解

文章主要来源于官网

https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-value-annotations

@Value 通常用于注入外部属性

@Component
public class MovieRecommender {

    private final String catalog;

    public MovieRecommender(@Value("${catalog.name}") String catalog) {
        this.catalog = catalog;
    }
}

使用以下配置类以及 application.properties 配置文件

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

如此这般,MovieRecommender 构造器的参数 catalog 以及字段 catlog 都将等于 MovieCatalog

Spring 内嵌了一个默认的宽松值解析器。它将尝试解析属性值,如果无法解析,${catalog.name} 则将注入属性名称作为值。如果要严格控制不存在的值,则应声明一个 PropertySourcesPlaceholderConfigurerbean

@Configuration
public class AppConfig {

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

不过,这个 Bean 已经在 SpringBoot 自动配置了,如果您使用的是 SpringBoot 则可以不用配置。

当使用 JavaConfig 方式配置的时候,@Bean 注解的方法必须是 static

 使用以上配置可以确保当任何 ${ } 占位符都没有被解析时,Spring 初始化会失败(通俗来说,就是抛出异常,程序退出)。

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'catalog.name' in value "${catalog.name}"

此外还可以通过 setPlaceholderPrefix, setPlaceholderSuffix, 或者 setValueSeparator 方法来自定义占位符,默认的占位符见下图:

由此可见,司空见惯地,如:@Value("${xxx.xxx}") 之类的配置,其中的 ${ } 只不过是 Spring 既定好的规则。

再次提及,Spring Boot  默认会配置 PropertySourcesPlaceholderConfigurer,并且从 application.properties 和 application.yml 获取属性。

Spring 内置的转换器允许简单类型的转换(如转换为 Integer 或 int)。多个逗号分隔的值将自动转换为 String[]。

支持提供默认值

@Component
public class MovieRecommender {

    private final String catalog;

    public MovieRecommender(@Value("${catalog.name:defaultCatalog}") String catalog) {
        this.catalog = catalog;
    }
}

实际上就是使用了一个冒号(:),后面跟着默认值

默认值的使用在 Spring 里也有体现,如:org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController,用于处理错误的控制器。

其中有一字段 org.springframework.boot.autoconfigure.web.ErrorProperties,存储着错误 URL。

这里就是使用了默认值 /error 

猜你喜欢

转载自blog.csdn.net/qq_39291919/article/details/108978287
今日推荐