特別提醒:一定要注意文件結構
webappapplication 一定要在包的最外層,否則spring無法對所有的類進行托管,會造成@autowired 無法注入。
1. 添加工具類獲取在 spring 中托管的 bean
?。?)工具類
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); } } |
?。?)使用
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