@Value注入问题
今天弄了一下午的@Value,总是获取不到值,百度搜结果不行。
原来问题
test:
name: hello world
package test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Md5Test {
@Value("test.name")
public String name;
@Test
public void main()
{
System.out.println(name);
}
}
获取到的name还是null,折腾了一下午还是没解决
解决方案:
后来,经过一个大佬指点。
他的原话是:
这个bean给spring管理 在别的地方注入他 就可以用 不要用自己new的对象,类似于 他已经给你把端口注入到bean里了 但是你只有通过spring的获取方式 才能拿到这个bean 也就是里面的值。
恍然大悟!
1.获取属性一定要放在springboot启动类下的包,要不然他无法扫描。
2.启动boot启动类
经过对比就可以看出来。需要把bean托管到spring容器中,然后在别的类注入这个bean才能获取到bean里的yml注入的属性。
总结:
1.@value一定要在@SpringBootApplication下扫描的类
2.在要注入的类中,需要@Autowired注入@value下的bean类(@Componet的类)
2.在别的类@Autowired注入@value下的bean类(@Comonet的类)
3.启动@SpringBootApplication的启动器