SpringBoot中使用@Value注解读取配置文件的属性值

目录

  • 注意事项一
  • 注意事项二


SpringBoot项目中使用 @Value 注解读取配置文件的属性值,将值赋给类中的属性,这是很常见的操作,示例如下:

@Component
public class User {

    @Value("${test.username}")
    public String username;
}

application.yaml 配置文件

test:
  username: tom

使用 @Value 注解有两点注意事项:

注意事项一:对象要交给 Spring 容器管理,也就是需要在类上加 @Component 等注解;

注意事项二:在静态变量上直接添加 @Value 注解是无效的。若要给静态变量赋值,可以在 set() 方法上加 @value 注解。

注意事项一

若对象不是由 Spring 容器管理,而是由我们手动 new 出来,那么 @Value 注解不能生效。示例如下:

public class User {

    @Value("${test.username}")
    public String username;
}
test:
  username: tom

测试:

@SpringBootTest
class MyTestApplicationTests {

    @Test
    public void test() {
        User user = new User();
        System.out.println("username: " + user.username);
    }

}

结果:

username: null

注意事项二

先演示直接在静态变量上添加 @Value 注解:

@Component
public class User {

    @Value("${test.username}")
    public static String username;
}
test:
  username: tom
@SpringBootTest
class MyTestApplicationTests {

    @Test
    public void test() {
        System.out.println("username: " + User.username);
    }

}

结果:

username: null

可见,在静态变量上直接添加 @Value 注解是无效的,正确的做法应是在 set() 方法上加 @value 注解。示例如下:

@Component
public class User {

    public static String username;

    @Value("${test.username}")
    public void setUsername(String username) {
        User.username = username;
    }
}
test:
  username: tom
@SpringBootTest
class MyTestApplicationTests {

    @Test
    public void test() {
        System.out.println("username: " + User.username);
    }

}

结果:

username: tom

如果有帮助的话,可以点个赞支持一下嘛

你可能感兴趣的:(Spring,spring,boot,后端,java,spring)