在Spring 的controller中要想使用service我们都会使用@Resource、@Autowired。但一般的类要使用service时,我们不能使用new主要是因为new出来的并不是由Spring容器进行管理的,因此new出来的service进行调用都会是null。
解决办法
一、普通类和工具类的解决办法
1、SpringContextUtils
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author clt
* @date 2019-12-10 15:37
*/
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
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 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的配置文件中配置
<bean id="SpringContextUtils" class="com.xxx.xxx.SpringContextUtils" scope="singleton"></bean>
3、使用方式
ApplicationContext applicationContext = SpringContextUtils.getApplicationContext();
xxxService xxxService = applicationContext.getBean(xxxService.class);