欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决Springboot @Autowired 无法注入问题

程序员文章站 2024-02-23 22:17:34
特别提醒:一定要注意文件结构   webappapplication 一定要在包的最外层,否则spring无法对所有的类进行托管,会造成@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;
/**
 * @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 无法注入问题,希望对大家有所帮助