在普通类中使用@service注释的类中的方法时会包空指针异常, 这种是因为,该普通类,没有加载到Spring容器中,所以获取由Spring容器管理的对象时获取不到,报出 java.lang.NullPointerException 空指针异常。一个困扰我好久的问题,最后在网上找到了解决办法,感谢那些大神。
解决办法:
定义工具类:
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException{
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = context;
}
}
/**
* 获取applicationContext
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过beanName获取bean
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return getApplicationContext().getBean(beanName);
}
/**
* 通过class获取bean
* @param clazz
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过beanName和class获得指定的bean
* @param beanName
* @param clazz
* @return
*/
public static <T> T getBean(String beanName , Class<T> clazz) {
return getApplicationContext().getBean(clazz, beanName);
}
}
如果使用注解式开发,要在类上加注解 @Component 。
如果使用配置式开发,要在 Spring 配置文件中加入 。
<bean id="springUtil" class="com.llangzh.utils.SpringUtil" scope="singleton" /> <!--class:工具类全名-->
目的都是为了将类交给 Spring 来管理,这样就可以通过工具类获得由 Spring 管理的对象了 。
应该注意的是,在使用工具类时:
getBean(String beanName) 方法参数是bean的名称,而不是想要检索的类名,eg:
@Service("studentService")
public class IStudentServiceImpl implements IStudentService{ }
参数应是:studentService
测试工具类:
在使用工具类之前,要保证 Spring 是处于启动状态,否则同样会报 java.lang.NullPointerException 空指针异常。
这里是我的测试代码:
@Test
public void run(){
//获取ApplicationContext对象
ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext("configfiles/spring.xml");
SpringUtil util = new SpringUtil();
//通过set方法启动Spring
util.setApplicationContext(ctx);
IStudentService service = (IStudentService) util.getBean(IStudentService.class);
IStudentService service1 = (IStudentService) util.getBean("studentService");
System.out.println(service);
System.out.println(service1);
}
控制台打印:
com.llangzh.services.impls.IStudentServiceImpl@2ae099cb
com.llangzh.services.impls.IStudentServiceImpl@2ae099cb
想要获得的 service 对象获得到了。
注意:
一、在获得service对象时不要new xxxService。Spring中的Service不是你想new就能new的,因为通过new实例化的对象脱离了Spring容器的管理,获取不到注解的属性值,所以会是null,就算调用service的类中有@Component注解加入了Spring容器管理,也还是null。
二、检查工具类上是否加了 @Component 注释,没有的要加上,或者在 Spring 配置文件中配置:
<bean id="springUtil" class="com.llangzh.utils.SpringUtil" scope="singleton" />(class:工具类全名)
这里是我的参考的大神的地址:https://blog.youkuaiyun.com/wqc19920906/article/details/80009929