解决SpringMvc中普通类注入Service为null的问题

SpringMvc中普通类注入Service为null

场景:

使用Quartz定时器时,普通的java类需要注入spring的service类,在调用时报错!

解决方式:

    /**
     * 定时获取课程的service
     */
    @Autowired
    protected QuartzGetCourseService quartzGetCourseService = (QuartzGetCourseService) SpringContextUtil
            .getBean("quartzGetCourseService");
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 在Spring 注解中,普通类获取@Service标记的方法或者bean对象
 *
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 注意 bean name默认 = 类名(首字母小写) 例如: A8sClusterDao = getBean("a8sClusterDao")
     *
     * @param name
     * @return
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * 根据类名获取到bean
     *
     * @param <T>
     * @param clazz
     * @return
     * @throws BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBeanByName(Class<T> clazz) throws BeansException {
        try {
            char[] cs = clazz.getSimpleName().toCharArray();
            cs[0] += 32;// 首字母大写到小写
            return (T) applicationContext.getBean(String.valueOf(cs));
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }
}

调用结束,测试可以获取Service.

spring之工具类使用service注入

一般需要在一个工具类中使用@Autowired 注解注入一个service。但是由于工具类方法一般都写成static,所以直接注入就存在问题。

栗子:

@Component
public class SmsController {
    private static Logger logger = LoggerFactory.getLogger(SmsController.class);
    @Autowired
    private MessagesInfoService messagesInfoService;
    private static SmsController smsController;     

    @PostConstruct
    public void init() {
        smsController = this;
        smsController.messagesInfoService = this.messagesInfoService;
    }  

    /**
     *短信历史查询接口(查询某个时间段发送的短信)
     */
    @RequestMapping(value = "/queryMessage",method = RequestMethod.GET)
    public ModelAndView queryMessage{
        pager = messagesInfoService.findPager(map,5,pIndex);
        ModelAndView modelAndView = new ModelAndView("manage/jgdxgl/jgdx_qm");
        List<MessagesInfo> list = pager.getItem();
        modelAndView.addObject("pager",pager);
        modelAndView.addObject("list",list);
        return modelAndView
    }
}  

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringMVC日期类型接收空值异常问题解决方法

    最近遇到SpringMVC写个controller类,传一个空串的字符类型过来,正常情况是会自动转成date类型的,因为数据表对应类类型就是date的 解决方法是在controller类的后面加个注解: @InitBinder protected void initDateFormatBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); binde

  • 快速解决SpringMVC @RequestBody 用map接收请求参数的问题

    一:遇到个跨域调用,因为传个我的参数不定,所以需要通过map来接收参数并进行签名验证等操作 理所当然的写出了下面的代码,但是发现map里并没有获取到传来的key-value值 @RequestMapping(value = "/callback", produces = "text/html;charset=UTF-8") @ResponseBody public String callback(@RequestBody Map<String, String&

  • JAVA解决在@autowired,@Resource注入为null的情况

    使用SpringMVC或者SSH过程中,有时可能会遇到这么一个问题.就是在一个普通的JAVA类(不是controller也不是action类)中无法注入在spring配置文件中配置的bean. 比如你在一个普通java类想调用某个在spring中配置的service,你会发现不管你用@Resource还是@Autowired注解都无法注入,对象始终是null. 那是因为一般普通的Java类没有被spring代理,自然无法通过spring注入相关的对象.难道这样就不能调用了吗?这里提供下面一个类来

  • 在service层注入mapper时报空指针的解决

    在service层注入mapper时报空指针 今天又遇到一个极其刁钻的问题,废话不多说先上代码,测试单元 @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBoot_Run.class) @ContextConfiguration(locations = { "classpath:mybatis/mappers/RevMapper.xml" }) public class TestTransaction { @Au

  • 解决SpringMvc中普通类注入Service为null的问题

    SpringMvc中普通类注入Service为null 场景: 使用Quartz定时器时,普通的java类需要注入spring的service类,在调用时报错! 解决方式: /** * 定时获取课程的service */ @Autowired protected QuartzGetCourseService quartzGetCourseService = (QuartzGetCourseService) SpringContextUtil .getBean("quartzGetCourseSe

  • java静态工具类注入service出现NullPointerException异常处理

    目录 一般我们在controller层调用service时,只需要使用@Autowired注解即可,例如如下代码我们经常看到: @RestController @RequestMapping("business") public class BizResourceController { @Autowired private BusinessService businessService; @RequestMapping(path = "/queryYearList"

  • Java实现普通类注入service对象

    普通类注入service对象 找了很多办法,无论是加@Component还是编写工具类实现ApplicationContextAware,始终为null. 最后使用这两行代码解决: WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); DailySurveyService service = (DailySurveyService) context.getBean("dailySurvey

  • 解决MyBatis中为类配置别名,列名与属性名不对应的问题

    在传参与接收返回结果的时候,咱们一直是使用的全限定名.但是MyBatis自己在使用很多类型的时候(如Integer,Boolean)却可以直接使用别名.那么,咱们自己的写的类能不能使用别名呢?可以.需要配置. mybatis配置文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//

  • springmvc 中dao层和service层的区别说明

    springmvc dao层和service层的区别 首先解释面上意思,service是业务层,dao是数据访问层 这个问题我曾经也有过,记得以前刚学编程的时候,都是在service里直接调用dao,service里面就new一个dao类对象,调用,其他有意义的事没做,也不明白有这个有什么用,参加工作久了以后就会知道,业务才是工作中的重中之重. 我们都知道,标准主流现在的编程方式都是采用MVC综合设计模式,MVC本身不属于设计模式的一种,它描述的是一种结构,最终目的达到解耦,解耦说的意思是你更改

  • 解决netty中spring对象注入失败的问题

    目录 netty中spring对象注入失败 发现了问题所在 在netty中注入spring成份 可以通过以下方式 netty中spring对象注入失败 今天在做项目的时候发现在netty中注入service失败,百度许久后也找不到答案(@Component,@PostConstruct)未起作用,后灵光一现 发现了问题所在 如图: 这些地方都必须通过spring注入才能实现其他依赖注入,之前这里都是采用new的,所以导致spring注入失败 在netty中注入spring成份 前不久,在Nett

  • SpringBoot集成shiro,MyRealm中无法@Autowired注入Service的问题

    网上说了很多诸如是Spring加载顺序,shiroFilter在Spring自动装配bean之前的问题,其实也有可能忽略如下低级错误. 在ShiroConfiguration中要使用@Bean在ApplicationContext注入MyRealm,不能直接new对象. 道理和Controller中调用Service一样,都要是SpringBean,不能自己new. 错误方式: @Bean(name = "securityManager") public SecurityManager

  • java实现在普通类中注入service或mapper

    普通类中注入service或mapper 1.类加@Component注解 2.注入需要引入的service @Autowired private UserService userService; 3.建静态文件 private static UserService users; 4.初始化方法 @PostConstruct public void init() { users= userService; } 5.调用 users.selectUser(user); mapper为null的情况

  • springboot实现在工具类(util)中调用注入service层方法

    一.新建BeanUtil类 import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.Applic

  • 解决Spring Boot 多模块注入访问不到jar包中的Bean问题

    情景描述 一个聚合项目spring-security-tutorial,其中包括4个module,pom如下所示: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://mav

随机推荐