工具类中采用静态注入的方式来注入bean
方式一:
@Component public class CommonUtils { private static SwitchConfig switchConfig; @Autowired public void setSwitchConfig(SwitchConfig switchConfig) { CommonUtils.switchConfig = switchConfig; } /*** * *工具类的静态方法 ***/ public static String getSwitchValue(String key){ return switchConfig.getValue(key); } }
总结:
1.需要对工具类增加@Component 注解;
2.将要注入的bean在工具类中申明下,用static修饰下;
3.给要注入的bean生成setter方法,切记一定不能是静态的,同时要用注解@Autowired;
4.然后再这个工具类中的静态方式里使用了;
方式二:
@Component public class CommonUtils { @Autowired private SwitchConfig switchConfig; private static CommonUtils commonUtils; @PostConstruct public void init() { commonUtils = this; } /*** * *工具类的静态方法 ***/ public static String getSwitchValue(Sting key) { return commonUtils.switchConfig.getValue(key); } }
总结:
1.需要对工具类增加@Component 注解;
2.@Autowired 注解注入bean;
3.@PostConstruct 使用该注解定义init()方法,在方法中给当前对象赋值,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;
方式三:
xml中配置bean
<!--spring容器中配置要注入的bean -->
<bean id="commonUtil" class="com.ambitious.CommonUtil" init-method="init">
<property name="switchConfig" ref="switchConfig" />
</bean>
代码中引用
@Component public class CommonUtils { private static SwitchConfig switchConfig; /** * set方法 * @param switchConfig */ public static void setVenderInfoService(SwitchConfig switchConfig) { CommonUtils.switchConfig = switchConfig; } public static String getSwitchValue(String key) { return switchConfig.getValue(key); } }
————————————————
版权声明:本文为CSDN博主「zhangfx5」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010526028/article/details/106807907
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?