在学习SSM框架时,突然发现工具类用@Autowired无法注入到工具类的静态属性。在查阅众多大佬的博客后发现了可行的办法。
1.使用@PostConstruct
@Autowired private IMenuService service; public void setService(IMenuService service) { this.service = service; } public static MenuUtils menuUtils; @PostConstruct public void init() { menuUtils=this; menuUtils.service=this.service; }
注意 同时需要在spring的配置文件里添加对工具类的扫描,不然同样无法运行
<context:component-scan base-package="***.***.util"/>
或者将类的懒加载关闭,即设置为false(有博主提到会导致System.getProperty读根目录变量时读到的是null)
<bean id="menuUtils" class="com.wjb.util.MenuUtils" init-method="init" lazy-init="false"> </bean>
(这其中还涉及了一点java类的加载,后期补充)
如有错误,还望斧正!