Spring MVC 中一般 普通類調用service


Spring MVC中一般 普通類調用service

在Spring MVC中,Controller中使用service只需使用注解@Resource就行,但是一般類(即不使用@Controller注解的類)要用到service時,可用如下方法:

1、SpringContextUtil

復制代碼
package com.test.framework.utils;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
public class SpringContextUtil implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext; // Spring應用上下文環境
 
    // 下面的這個方法上加了@Override注解,原因是繼承ApplicationContextAware接口是必須實現的方法
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
 
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
* 通過類獲取對象
* @param clazz
*/
public static Object getBean(Class<?> clazz) {
return applicationContext.getBean(clazz);
}
    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 boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
 
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }
 
    public static Class getType(String name)    throws NoSuchBeanDefinitionException {
        return applicationContext.getType(name);
    }
 
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(name);
    }
}
復制代碼

2、Spring的配置文件application.xml中進行如下配置

<bean id="SpringContextUtil" class="com.test.framework.utils.SpringContextUtil" scope="singleton" lazy-init="false" 
></bean>

3、使用

private HzTakenService hzTakenService = (HzTakenService) SpringContextUtil.getBean(HzTakenService.class);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM