Spring实现如何在工具类中调用Service方法

1、首先在spring-mvc.xml中增加注解

 <!-- 扫描util -->
<context:component-scan base-package="com.essbase.util.springToutil">      </context:component-scan>

2、引入工具类SpringContextUtil.java

package com.essbase.util.springToutil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * @author lenovo
 *
 */
@Component//注意要添加这个注解,否则获取不到数据
public class SpringContextUtil implements ApplicationContextAware {
     
	private static ApplicationContext applicationContext;
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
     
		if (SpringContextUtil.applicationContext == null) {
     
			SpringContextUtil.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){
     
		return getApplicationContext().getBean(clazz);	
	}
	public static <T>T getBean(String name, Class<T> clazz){
     
		return getApplicationContext().getBean(name,clazz);
	}
   }

3、在工具类中调用

ApplicationContext appCtx = SpringContextUtil.getApplicationContext();
LoginService loginService = appCtx.getBean(LoginService.class);

你可能感兴趣的:(JAVA基础总结,java,spring)