软件编程
位置:首页>> 软件编程>> java编程>> 解决Springboot @Autowired 无法注入问题

解决Springboot @Autowired 无法注入问题

作者:不靠谱斯基  发布时间:2022-04-14 21:19:01 

标签:spring,boot,注入

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

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 无法注入问题网站的支持!

来源:https://www.cnblogs.com/sylarken/archive/2018/08/07/9435076.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com