解决Springboot @Autowired 无法注入问题
时间:2021-12-03 09:26:32|栏目:JAVA代码|点击: 次
特别提醒:一定要注意文件结构
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");
}
}
总结
上一篇:springmvc+ajax+formdata上传图片代码实例
栏 目:JAVA代码
本文标题:解决Springboot @Autowired 无法注入问题
本文地址:http://www.codeinn.net/misctech/185592.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




