Springboot中如果希望在Utils工具类中,使用到我们已经定义过的Dao层或者Service层Bean,可以如下编写Utils类:
-
使用@Component注解标记工具类MD5StringUtil :
-
使用@Autowired(@Autowired和@Resource的区别不再介绍)注入我们需要的bean:
-
在工具类中编写init()函数,并使用@PostConstruct注解标记工具类,初始化Bean:
@Component
public class StringUtil {
@Resource
private EncryptProperties encryptProperties;
@Value("${server.port}")
private String port;
// 维护一个本类的静态变量
private static StringUtil stringUtil;
@PostConstruct
public void init() {
stringUtil= this;
stringUtil.encryptProperties = this.encryptProperties;
stringUtil.port = this.port;
}
public static String longyuanMd5Hex(byte[] bytes) {
//return stringUtil.encryptProperties.getSalt();
return stringUtil.port;
}
}