Springboot 工具类中注入Value失败

在工具类中,通过@Value的形式,获取配置失败,但是同样的写法在Controller中却成功了,而且在这个工具类的单元测试文件中也能获取到配置。
尝试在这个工具类上加入@Controller注解,@Service注解,@Component注解均无法获取。

补充说明:版本为springboot1.5.12,配置文件为yml文件

问题找到了,在调用AuthUtil的类中,没有使用Spring容器管理,而是用了new创建的,所以导致出现这个问题。





import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;


@Component
public class AuthUtil {

    private String timestamp;

    private String httpBody;

    @Value("${bindInfo.bind.secret}")
    private String secret;

    @Value("normal")
    private String normal; // 注入普通字符串

    /*
  * 计算1970-01-01到当期时间的时间戳
  */
    public String getTimestamp() {
        long startPaintLogoTime=System.currentTimeMillis();
        return String.valueOf(startPaintLogoTime / 1000);
    }

    public String getHttpMD5(String timestamp, String httpBody){
        this.timestamp = timestamp;
        this.httpBody = httpBody;
        System.out.println(">>>>>>>>>>>>>>>>>>"+timestamp + secret +httpBody);
        System.out.println(normal);
        return  DigestUtils.md5Hex( timestamp + secret +httpBody ).toUpperCase();
    }

    public static void main(String[] args) {
        AuthUtil authUtil = new AuthUtil();
        authUtil.getHttpMD5(authUtil.getTimestamp(),"ksksksks");
    }
}

 @RunWith(SpringRunner.class)
@SpringBootTest
public class AuthUtilTest {

    @Value("${bindInfo.bind.secret}")
    private String secret;

    @Test
    public void getTimestamp() {
        System.out.println(">>>>>>>>>>>>>>>>.."+secret);
    }


}

不能再main方法中运行,你既然使用spring的东西就要,将对象的管理交予spring容器
需要加载spring容器通过容器管理对象。

pom.xml

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

在项目中src下创建test/目录用于存放test累
ApplicationTest.java

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRoleMapperTest {

@Autoware
private AuthUtil authUtil;
    @Test
    public void test1() throws IOException, WorkbookDataException {
        authUtil.getHttpMD5(authUtil.getTimestamp(),"ksksksks");
        }
    }
}

这不是最佳的答案,还有一种方法我见过但是不会,但是首先还是要在容器中运行的,只在main方法中是无法加载容器相关的东西的

yml文件有问题吧,你仔细看一下,是否只有一个空格在名称和值之间

主要看你怎么使用的AuthUti类,使用它要让Spring来注入,就是用@Autowired的方式注入,不能用new AuthUtil()的方式自己创建,如果是用new创建的AuthUtil的话@Value就会失效