spring boot 无法注入 解决Springboot @Autowired 无法注入问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring boot 无法注入 解决Springboot @Autowired 无法注入问题

不靠谱斯基   2021-03-31 我要评论

特别提醒:一定要注意文件结构

  WebappApplication 一定要在包的最外层,否则Spring无法对所有的类进行托管,会造成@Autowired 无法注入。

1.  添加工具类获取在 Spring 中托管的 Bean

  (1)工具类

package com.common;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
 * @program: IPC_1P
 * @description: 获取在spring中托管的bean
 * @author: johnny
 * @create: 2018-08-03 16:24
 **/
public class SpringContextUtil {
  private static ApplicationContext applicationContext; // Spring应用上下文
  // 下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法
  public static 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);
  }
}

  (2)使用

    1)程序启动时,实例化 SpringContextUtil

@SpringBootApplication
public class WebappApplication {
  private static ApplicationContext applicationContext;
  public static void main(String[] args) {
    applicationContext = SpringApplication.run(WebappApplication.class, args);
    //
    SpringContextUtil springContextUtil = new SpringContextUtil();
    springContextUtil.setApplicationContext(applicationContext);
    System.out.println("服务器启动测试!");
}

    2)在使用 @Service 的方法中,通过@Autowired 注入,使用SpringcontexUtil 获取Bean上下文

@Autowired
  SenderService senderService;
public class Package_State {
  @Autowired
  SenderService senderService;
  @Component
  private Package_State() {
    senderService = (SenderService)SpringContextUtil.getBean("senderService");
  }
}

总结

以上所述是小编给大家介绍的解决Springboot @Autowired 无法注入问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们