springMVC和Springboot项目@value注解值为null的解决办法

最近springMVC项目和springboot项目都遇到用@value获取配置文件中配置项值为空的情况,以下是我的解决方法:

springMVC项目解决方法:

service-context文件中增加下面配置:

<context:component-scan base-package="com.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

以上配置用来扫描项目包名下的所有类

由于我service层和common模块都需要获取配置文件中配置项的值,但是添加上面的配置后,我只能在service层通过@value获取到配置项的值,common模块仍然无法获取到配置项的值

springboot项目解决方法:

需要在类添加@Component注解

例如:

@Component
public class TestUtil {

  public static boolean enable;

  @Value("${enable}")
  public void setEnable(boolean enable) {
    TestUtil.enable = enable;
  }

}

注意事项:

1.@value获取值为null,可能是由于使用static、final修饰变量名:

@Value("${enable}")

public static boolean enable; //获取值为null

2.一个static修饰的变量需要使用到@value获取到值的变量,需要添加@PostConstruct

例如:

@Component
public class TestUtil {

  public static String url;

  @Value("${url}")
  public void setEnable(String url) {
    TestUtil.url = url;
  }

  private static String uri;
  @PostConstruct
  public void init() {
    uri = "http://" + uri;
  }

}

3.接收变量为int、long类型的值需要如下接收

@Value("#{${bandwidth}}")
 public Long bandwidth;

猜你喜欢

转载自www.cnblogs.com/Bud-blog/p/12167926.html