解决Springboot @Autowired 无法注入问题

时间:2022-11-08 22:33:29

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

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

1.  添加工具类获取在 spring 中托管的 bean

  (1)工具类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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

?
1
2
3
4
5
6
7
8
9
10
@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上下文

?
1
2
3
4
5
6
7
8
9
10
@autowired
  senderservice senderservice;
public class package_state {
  @autowired
  senderservice senderservice;
  @component
  private package_state() {
    senderservice = (senderservice)springcontextutil.getbean("senderservice");
  }
}

总结

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

原文链接:https://www.cnblogs.com/sylarken/archive/2018/08/07/9435076.html