Spring Boot @Value

本文介绍 Spring Boot 2 外部化配置实现方案中 @Value 的使用。


目录

  • 开发环境
  • 基础示例
  • @Value 详解
  • 示例:@Value 修饰属性
  • 示例:@Value 修饰方法
  • 备注

开发环境

  • Oracle JDK 1.8.0_201
  • Apache Maven 3.6.0
  • IntelliJ IDEA (Version 2018.3.3)

基础示例

  1. 创建 Spring Boot 工程,参考:IntelliJ IDEA 创建 Spring Boot 工程

  2. 生成的 pom 文件如下,不做任何修改

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>tutorial.spring.boot</groupId>
    <artifactId>spring-boot-configuration</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-configuration</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 工程 src/main/resources 目录下自动生成了一个配置文件 application.properties,向此配置文件中添加以下内容。
tutorial.spring.boot.configuration.welcome=Welcome to Spring Boot Configuration Tutorial!
  1. 新建一个类 WelcomeConfig,使用 @Configuration 注解标识这是个配置类,在构造函数中使用注解 @Valueapplication.properties 配置文件中 tutorial.spring.boot.configuration.welcome 的值注入到参数 welcome 中。
package tutorial.spring.boot.configuration.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WelcomeConfig {

    public WelcomeConfig(@Value("${tutorial.spring.boot.configuration.welcome}") String welcome) {
        System.out.println(welcome);
    }
}
  1. 启动运行。
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-03-16 10:15:59.500  INFO 9888 --- [           main] s.b.c.SpringBootConfigurationApplication : Starting SpringBootConfigurationApplication on ... with PID 9888 (D:\Tutorial\spring-boot-configuration\target\classes started by ... in D:\Tutorial\spring-boot-configuration)
2019-03-16 10:15:59.504  INFO 9888 --- [           main] s.b.c.SpringBootConfigurationApplication : No active profile set, falling back to default profiles: default
Welcome to Spring Boot Configuration Tutorial!
2019-03-16 10:16:00.167  INFO 9888 --- [           main] s.b.c.SpringBootConfigurationApplication : Started SpringBootConfigurationApplication in 1.083 seconds (JVM running for 1.889)

@Value 详解

@Value 注解不仅可以修饰参数,还可以修饰属性和方法,参考 @Value 源码。

package org.springframework.beans.factory.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value();
}

示例:@Value 修饰属性

  1. 修改 WelcomeConfig 类。
package tutorial.spring.boot.configuration.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class WelcomeConfig {

    @Value("${tutorial.spring.boot.configuration.welcome}")
    private String welcome;

    @PostConstruct
    public void init() {
        System.out.println(welcome);
    }
}

注意:
(1) 因为 @Value 未直接修饰构造器参数,所以构造器执行过程中 welcome 属性值仍为 null,实际在对象构造完成后执行的属性注入;
(2) @PostConstruct 注解作用是 WelcomeConfig 对象构造完成后执行,此处使用 @PostConstruct 注解只是为了演示属性可正常注入,更多有关 @PostConstruct 注解的用法在此不做详细讨论。

  1. 启动运行。
......
2019-03-16 10:35:42.964  INFO 9988 --- [           main] s.b.c.SpringBootConfigurationApplication : Starting SpringBootConfigurationApplication on ... with PID 9988 (D:\Tutorial\spring-boot-configuration\target\classes started by ... in D:\Tutorial\spring-boot-configuration)
2019-03-16 10:35:42.968  INFO 9988 --- [           main] s.b.c.SpringBootConfigurationApplication : No active profile set, falling back to default profiles: default
Welcome to Spring Boot Configuration Tutorial!
2019-03-16 10:35:43.629  INFO 9988 --- [           main] s.b.c.SpringBootConfigurationApplication : Started SpringBootConfigurationApplication in 1.071 seconds (JVM running for 1.891)

示例:@Value 修饰方法

  1. 修改 WelcomeConfig 类。
package tutorial.spring.boot.configuration.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class WelcomeConfig {

    private String welcome;

    @PostConstruct
    public void init() {
        System.out.println(welcome);
    }

    @Value("${tutorial.spring.boot.configuration.welcome}")
    public void setWelcome(String welcome) {
        this.welcome = welcome;
    }
}
  1. 启动运行。
......
2019-03-16 10:40:16.930  INFO 9268 --- [           main] s.b.c.SpringBootConfigurationApplication : Starting SpringBootConfigurationApplication on ... with PID 9268 (D:\Tutorial\spring-boot-configuration\target\classes started by ... in D:\Tutorial\spring-boot-configuration)
2019-03-16 10:40:16.935  INFO 9268 --- [           main] s.b.c.SpringBootConfigurationApplication : No active profile set, falling back to default profiles: default
Welcome to Spring Boot Configuration Tutorial!
2019-03-16 10:40:17.587  INFO 9268 --- [           main] s.b.c.SpringBootConfigurationApplication : Started SpringBootConfigurationApplication in 1.057 seconds (JVM running for 1.842)

备注

与本例中 application.properties 等效的 YAML 配置文件内容如下。

tutorial:
  spring:
    boot:
      configuration:
        welcome: Welcome to Spring Boot Configuration Tutorial!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容