栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

解决Springboot @Autowired 无法注入问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决Springboot @Autowired 无法注入问题

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

  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;

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 无法注入问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140280.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号