SSM在普通Java類裡使用service、dao等
阿新 • • 發佈:2019-01-22
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * 通過該類即可在普通工具類裡獲取spring管理的bean * 注意:需要在spring-mybatis.xml 新增 <bean class="com.gx.util.SpringTool"/> * @author wolf * http://blog.csdn.net/tianyaleixiaowu/article/details/54630383 */ @Component public final class SpringTool implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringTool.applicationContext == null) { SpringTool.applicationContext = applicationContext; //System.out.println( "========ApplicationContext配置成功,在普通類可以通過呼叫ToolSpring.getAppContext()獲取applicationContext物件,applicationContext="+ applicationContext + "========"); } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } public static <T>T getBean(Class<T> clazz) { // TODO Auto-generated method stub return getApplicationContext().getBean(clazz); } }
2. 配置檔案 :在spring-mybatis.xml 新增 <bean class="com.liner.util.SpringTool"/>
3.普通類中呼叫:
public class ServiceTest { public List<UserVo> getData(){ IUserService articleService = SpringTool.getBean(IUserService.class); List<UserVo> list = articleService.findUserVoAll(); return list; } }