spring 基类获取注入ApplicationContext

工具类

package com.mer.conn;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public 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.对应的基类" />

猜你喜欢

转载自blog.csdn.net/qq_25384901/article/details/78845833