在编写工具类 提供方法的时候由于要注入service层,在编写的时候发现service层类注入失败,由于普通类不是通过spring进行管理的,所有注入service会失败。所以可以采用下面的方法。
SpringTool需要加到spring配置中,如果采用自动扫描需要将springtool声明为组件。添加@Component
package com.xx;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* SpringTool
* @author guoyupeng
* @version 1.0
*
*/
@Component
public class SpringTool implements ApplicationContextAware{
/**
* applicationContext 对象
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringTool.applicationContext == null){
SpringTool.applicationContext = applicationContext;
}
}
/**
* @return the applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据bean名称获取 spring实例 <br/>
* 注意:spring 默认的bean的名称 一般为bean实现类 的首字母小写的类名 <br/>
* eg:LogServiceImpl 如果没有指定bean的名称 则bean一般默认为:logServiceImpl
* @param name
* @return
*/
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
}
具体使用
private LogService = (LogService)SpringTool.getbean("logServiceImpl");
注意:获取spring 需要在配置文件进行配置,并且bean的名称要和spring中的bean名称一致,否则会取不到spring实例。
还有一种方法:
不依赖于servlet,不需要注入的方式
注意一点,在服务器启动时,Spring容器初始化时,不能通过以下方法获取Spring 容器。
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
wac.getBean(beanID);