在做项目的时候突然有这样一个需求,在工具类中需要注入spring组件,由于工具类都是静态的直接注入或者new一个类都是不行的,因此了解了一下相关用法.
我的项目里是将一个自定义的文件上传路径写在配置文件中,然后在文件工具类中使用它.相关关键代码如下
@Component
public class FileUtil {
private static FileUtil fileUtil;
@Autowired
private ProjectProperties projectProperties;
@PostConstruct
public void init() {
fileUtil = this;
fileUtil.projectProperties = this.projectProperties;
}
/**
* 获取图片根目录
*
* @return
*/
public static String getImgBasePath() {
String os = System.getProperty("os.name");
String basePath;
if (os.toLowerCase().startsWith("win")) {
basePath = "D:/projectdev/image/";
} else {
basePath = fileUtil.projectProperties.getFilePathProperties().getBasePath();
}
basePath = basePath.replace("/", SEPERATOR);
return basePath;
}
}
以上就可以实现在静态类中注入依赖了.
注: