在Spring MVC的架构中,如果希望在程序中直接引用properties中定义的配置值,通常是使用@Value注解的方式来获取:

@Value("${tagKey}")
private String tagValue;

但是取值的时候却可能会发现这个tagvalue的值为NULL,可能原因有:

1.使用了【static】修饰符或【final】修饰符修饰了tagValue。

private static String tagValue; // 错误
private final String tagValue; // 错误

这样导致了tagValue的值不可改变,注解无法注入配置值。

2.在类上没有加@Component注解(或者@service注解等)。

@Component // 必须要加上
class TestTagValue {
    @Value("${tagKey}")
    private String tagValue;
}

类上没有相应注解不能使该类被Spring容器统一管理,注解无法注入配置值。

3.使用new关键字新建了一个实例,而不是使用@Autowired注解。

@Component   
class TestTagValue{
    @Value("${tagKey}")
    private String tagValue;
}

@Service
class TestService {
    // 取得到tagValue值
    @AutoWired
    private TestTagValue testTagValue;
    
    // 取不到tagValue值
    TestTagValue testTagValue1 = new TestTagValue();
}

取不到的原因和2类似,在默认的情况下交由Spring容器管理的类是单例模式的,使用new关键字脱离了Spring容器的管理,成员变量值没有被注入。

 

"我走过万千世界,最后在心底留下一片荒原。"

相关文章:

  • 2022-12-23
  • 2021-12-29
  • 2021-07-12
  • 2021-10-06
  • 2022-01-20
  • 2021-08-18
  • 2021-05-17
  • 2021-09-08
猜你喜欢
  • 2022-12-23
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2023-03-30
  • 2021-07-01
相关资源
相似解决方案