首先说一下ApplicationContext这个类,bean工厂,applicationContext说白了就是对beanFactory的扩展,也就是一个spring容器,而且applicationContext是单例的。
配置一下,就这么一句话在spring里面
<bean class="com.prj.utils.mUtils.SpringTool"/>
然后在你的代码里面设置一下就ok了
private static YordergoodsService yordergoodsService =(YordergoodsService)UfdmContextHelperUtil.getBean("yordergoodsServiceImpl");
然后你启动项目就能在你的工具类或者其他地方直接调service
=================================================================================
经过楼主学习发现上面的方式 用起来比较简单但是总缺了点什么,现在补充点知识
package org.springframework.context;
//spring里面有这个接口提供扩展
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
然后继承这个类重写这个方法SpringBeanUtil
package com.mxc.web.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringBeanUtil() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
public static ApplicationContext getContext() {
return applicationContext;
}
}
当你拿到了applicationContext的时候你就可以调用里面的方法为所欲为
当然上面那个类要被spring扫到不然读取不了,如果是springboot的则放到同级目录或者子级下,或者手动 @import加载。
反正你要他成为bean就行了