(亲测有效。)Spring MVC中,Controller中使用service只需使用注解,但是普通类获取 service或 dao 都是null空的。

在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对象了。后面就能获取它的方法。进行操作了。

 

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值