在springmvc中,controller中可以通过注解
@Autowired 获取你的service层调方法。但是普通的工具类中调用service层。老是报null空指针。用new 对象可以,但是Dao层又开始报空指针。所以就获取不到dao层的方法。不能进行增删改查操作。
通过下面的上下文类。可以解决这一国际难题。这特殊情况下的问题。就用这种特殊方法来解决。
获取上下文的工具类:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Created by Administrator on 2017/9/29.
*/
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;
}
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);
}
}
spring-mvc.xml中添加配置:
<bean id="SpringContextUtil" class="com.mytest.modules.util.SpringContextUtil" scope="singleton"></bean>
MyService myservice= (MyService ) SpringContextUtil.getBean("myservice");
myservice.save(XXX);
这样就能得到 service对象了。后面就能获取它的方法。进行操作了。