在使用@Value的时候,可以从properties文件中获取值,这样做可以解耦,但是今天在使用这个注解的时候即使赋值,却只能取到null
主要错误:
1.没有在类上使用@Component注解或其他衍生注解,使之成为容器,spring就获取不到properties的值。
2.在调用这个类的时候,没有使用@Autowired使其自动注入,而是使用了new的方式,这样也取不到值。

下面是正确方法:

  • Util类
...
@Component    //必须加
public class BmsUtil {
	@Value("${file.uploadFolder}")
	private String realBasePath;
	...
}
  • Service类
...
@Service //必须加,@Service是@Component的衍生注解
public class BookServiceImpl implements BookService {
	@Autowired
	BookMapper bookMapper;
	@Autowired  //在调用类的时候,需要用@Autowired自动注入
	BmsUtil bmsUtil;
	...
}
  • properties
spring.thymeleaf.cache=false
#设置sql语句输出在控制台
logging.level.com.muyu.bms.mapper=debug
#windows上传图片路径
file.uploadFolder=E:/code/IDEA code/BMS/src/main/resources/static/upload
#linux上传图片路径
#file.uploadFolder=/usr/local/tomcat/apache-tomcat/webapps/ROOT/WEB-INF/classes/static/upload

另有一种情况@Value也不能获取到值,是在构造函数中调用了@Value作用的变量,并为其赋值。

================================
时间久了再回头看这个问题,其实已经很好理解了,@Value是Spring,IOC注入参数的一种方式,所以必须加上@Component等衍生注解,将其交给Spring管理,@Autowired也是一样的道理,使用这个注解Spring才会把值注入进去。
而调用构造函数创建对象,@Value获取不到值的原因就是,你没有使用Spring的获取对象的方法,自己创建了一个对象,自然也就拿不到Spring注入的值。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐