spring 基类获取注入ApplicationContext

来源:互联网 发布:维多利亚秘密 知乎 编辑:程序博客网 时间:2024/06/07 11:29

工具类

package com.mer.conn;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class SpringContextUtils implements ApplicationContextAware {       private static ApplicationContext applicationContext = null;          public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {              SpringContextUtils.applicationContext = applicationContext;          }          public static ApplicationContext getApplicationContext() {              return applicationContext;          }          public static Object getBean(String name) throws BeansException {              return applicationContext.getBean(name);          }          public static Object getBean(String name, Class requiredType) throws BeansException {              return applicationContext.getBean(name, requiredType);          }          public static <T> T getBean(Class<T> requiredType,String name ) throws BeansException {              return applicationContext.getBean(name, requiredType);          }                public static boolean containsBean(String name) {               return applicationContext.containsBean(name);          }  }

使用:
1. 基类

public static DfbalanceServiceImpl  dfserver =(DfbalanceServiceImpl)SpringContextUtils.getBean("dfbalanceServiceImpl");    @SuppressWarnings("unchecked")    public static void doDeal(String reqBosy,String path) throws Exception {        dfserver.dfcl(reqBosy,path);    }
  1. ServiceImpl
添加注解 : @Service("dfbalanceServiceImpl")public class DfbalanceServiceImpl extends BaseServiceImpl<Dfbalance,Integer> implements DfbalanceService{    @Resource    private DfbalanceDao dfbalanceDao;    @Resource    public void setBaseDao(DfbalanceDao dDao) {        super.setBaseDao(dfbalanceDao);    }    @Override    public void dfcl(String infoString,String path) throws Exception {    //调用方法执行sql    }
  1. 如果未获取到对象 则看下配置文件
<context:component-scan base-package="com.md.controller" />修改为<context:component-scan base-package="com.md.*" />或者<context:component-scan base-package="com.md.对应的基类" />
原创粉丝点击