当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot使用Value注解给静态变量赋值的方法

Spring Boot使用Value注解给静态变量赋值的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

昨天在使用@value注解给静态变量赋值的时候,发现静态变量的值始终是null。后来搜索一下得知其中原因,spring boot 不允许/不支持把值注入到静态变量中。但是我们可以变通一下解决这个问题。因为spring boot 支持set方法注入,我们可以利用非静态set方法注入静态变量。废话不多说,贴上我昨天写的代码:

@component
public class coverimageutil {

  private static string endpoint;

  private static string bucketname;

  @value("${oss.endpoint}")
  private void setendpoint(string name){
    endpoint = name;
  }
  @value("${oss.bucketname}")
  private void setbucketname(string name){
    bucketname = name;
  }
  public static string getimage(string path){

    if (stringutils.isempty(path)){
      return null;
    }
    // xxx的图片地址 https://oss.xxx.com/uploads/8f/70/8f70879210f08aaa6f4a04a3d42f3704.jpg
    if (path.contains("oss.xxx.com")){
      return path;
    }
    string[] str = path.split(",");

    // mt的图片地址
    // key = customer/coverimg/1002,fafa5efeaf3cbe3b23b2748d13e629a1,418530,image/jpeg
    // url = https://m-t-tesing.oss-cn-hangzhou.aliyuncs.com/customer/coverimg/1002
    stringbuilder url = new stringbuilder("https://");
    url.append(bucketname)
        .append(".")
        .append(endpoint)
        .append("/")
        .append(str[0]);

    return url.tostring();
  }
}

注意

  • 代码中需要@component注解
  • set方法要是非静态的

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网