解决springboot关于@Autowired注入为null的问题

本文深入探讨了Spring框架中依赖注入的正确使用方法,对比了直接new对象与利用构造器注入的区别,强调了@Component注解在类上的作用,并通过具体示例展示了如何在工具类和Controller类中正确使用@Autowired注解来获取Service类实例,避免了因注入失败导致的空指针异常。

有些类不是controller在使用autowired注入的service类显示为null

  • 完美解决
  • 没有new

  • ps 使用@ConfigurationProperties(prefix = “xxxx”)时,在工具类例如 UserUtils 类封装方法,在RestController 类中 调用

//示例
@Component
public class DemoUtil{
    @Autowired
    private DemoPro demoPro; //@ConfigurationProperties(prefix = "xxxx") 读取Bean类

	public demo getDemo(){
	 String demothree = "123"
	  return demoTwoFun(demoPro.getBase64, demothree)
	}
 }
//错误示例
@RestController
public class Demo{
	@GetMapping("/getDemo")
	public demo getDemo(){
	  return new DemoUtil().getDemo()
	}
}
//——————————————————————————————分割线————————————————————————————————
//成功读取示例
@RestController
public class Demo{
	@Autowired
	private DemoUtil demoUtil;
	@GetMapping("/getDemo")
	public demo getDemo(){
	  return demoUtil.getDemo()
	}
}
//*******************工具 类*******************
@Component
public class DemoUtil{
    @Autowired
    private DemoMapper demoMpper;

	public demo getDemo(){
	  QueryWarpper query = new QueryWarpper<>();
	  query.eq("id",1)
	  return demoMpper.selectOne(query)
	}
 }
//*******************controller 类*******************

@RestController
public class Demo{
	@Autowired
	private DemoUtil demoUtil;
	@RequestMapping(value = "/getDemo", method = RequestMethod.POST)
	public demo getDemo(){
	  return demoUtil.getDemo()
	}
}
  • 第一种解决方式
@Component
public class ProductInstLogic {
    @Autowired
    private InstImpl instImpl;
    
    private static ProductInstLogic pil ;
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        pil = this;
        pil.InstImpl = this.instImpl;
        pil.ProductInstImpl = this.ProductInstImpl;
        // 初使化时将已静态化的testService实例化
    }
 }
  • 第二种解决方式
@Component
public class ProductInstLogic {
    @Autowired
    // @Resource
    private InstMapper InstMapper;
}
@Component
public class TimingAuto {
    @Autowired
    private ProductInstLogic productInstLogic;
    
    @Scheduled(cron = "0/10 * * * * ?") //10秒执行一次
    public void productInstSocket() {
       	productInstLogic.ProductInstAll();
    }
    
}
@RestController
public class ProductInstController {
    @Autowired
    private ProductInstLogic productInstLogic;
}
<think>好的,用户遇到了在Spring Boot 3中使用@Autowired注解时AdminMapper为null问题。我需要先分析可能的原因,然后根据提供的引用资料逐一排查。 首先,根据引用[1]和[2],注入null可能是因为Bean的生成顺序问题,或者是在非Spring管理的类中使用了@Autowired。比如用户可能在手动new的对象中尝试注入,这会导致失败,因为Spring无法管理这些实例。这时候需要确保AdminMapper所在的类本身是被Spring容器管理的,比如添加了@Component或@Service等注解。 其次,引用[3]提到在静态变量或线程中使用@Autowired会导致问题,因为Spring无法注入静态成员。如果用户将AdminMapper声明为static,那肯定会是null。需要检查代码中是否有这样的错误用法,并改为非静态变量。 然后,引用[4]指出访问权限的问题,如果注入方法或字段是private的,某些情况下会导致注入失败。虽然Spring通常能通过反射注入private字段,但最好还是将字段设为public或使用setter方法,确保注入成功。 接下来,可能的解决方案包括:检查类是否被Spring管理,确保AdminMapper有正确的注解如@Mapper或@Repository;检查是否有循环依赖;使用构造函数注入代替字段注入,因为构造函数注入更可靠,特别是在Spring Boot 3中可能更推荐这种方式。 另外,如果用户是在自定义的过滤器或Servlet等非Spring管理的组件中使用@Autowired,可能需要通过ApplicationContext手动获取Bean,如实现ApplicationContextAware接口,或者使用@Configurable注解。 还需要考虑是否在测试环境中正确配置了上下文,比如在单元测试中使用@SpringBootTest注解来启动完整的Spring上下文,避免在普通测试中无法注入的情况。 最后,建议用户检查依赖配置,确保Spring Boot 3的相关依赖正确,特别是如果AdminMapper是MyBatis的Mapper,需要确认是否添加了@MapperScan注解来扫描对应的接口。 总结一下,可能的解决步骤是:检查类是否被Spring管理,检查静态变量,检查访问权限,使用构造函数注入,处理非Spring管理的类,检查依赖配置和注解,以及处理测试环境的问题。</think>### Spring Boot 3中@Autowired导致AdminMapper为空的解决方案 #### 1. **检查类是否被Spring管理** - **问题**:如果包含`AdminMapper`的类未被Spring容器管理(例如未添加`@Component`、`@Service`、`@Controller`等注解),则无法通过`@Autowired`注入依赖。 - **解决方案**:确保类添加了合适的注解。例如: ```java @Service public class AdminService { @Autowired private AdminMapper adminMapper; } ``` #### 2. **避免静态变量注入** - **问题**:若将`AdminMapper`声明为`static`字段,Spring无法注入静态成员[^3]。 - **解决方案**:移除`static`关键字,改为非静态字段: ```java @Autowired private AdminMapper adminMapper; // 非static ``` #### 3. **检查访问权限** - **问题**:若字段或方法为`private`且未提供`public`的`setter`方法,可能导致注入失败(尤其在旧版本Spring中)[^4]。 - **解决方案**:将字段设为`public`或提供`setter`方法: ```java @Autowired public void setAdminMapper(AdminMapper adminMapper) { this.adminMapper = adminMapper; } ``` #### 4. **使用构造函数注入(推荐)** - **问题**:字段注入(`@Autowired`直接标注字段)可能因Bean初始化顺序导致问题。 - **解决方案**:改用构造函数注入,Spring Boot 3推荐此方式: ```java @Service public class AdminService { private final AdminMapper adminMapper; public AdminService(AdminMapper adminMapper) { this.adminMapper = adminMapper; } } ``` #### 5. **处理非Spring管理的类** - **问题**:在手动`new`的类(如工具类、过滤器、线程)中无法直接使用`@Autowired`[^2]。 - **解决方案**: - **方法1**:通过`ApplicationContext`手动获取Bean: ```java @Component public class MyUtils implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) { context = applicationContext; } public static AdminMapper getAdminMapper() { return context.getBean(AdminMapper.class); } } ``` - **方法2**:使用`@Configurable`注解(需开启AspectJ支持): ```java @Configurable public class CustomClass { @Autowired private AdminMapper adminMapper; } ``` #### 6. **检查Mapper接口配置** - **问题**:若`AdminMapper`是MyBatis接口,需确保正确配置`@Mapper`或`@MapperScan`。 - **解决方案**: ```java @Mapper public interface AdminMapper { // SQL方法 } ``` 或在启动类添加扫描: ```java @SpringBootApplication @MapperScan("com.example.mapper") public class Application { ... } ``` #### 7. **排除循环依赖** - **问题**:若`AdminService`与`AdminMapper`存在循环依赖,可能导致Bean初始化失败。 - **解决方案**:重构代码逻辑,或使用`@Lazy`延迟注入: ```java @Autowired @Lazy private AdminMapper adminMapper; ``` #### 8. **测试环境配置** - **问题**:单元测试中未正确加载Spring上下文。 - **解决方案**:使用`@SpringBootTest`注解: ```java @SpringBootTest class AdminServiceTest { @Autowired private AdminMapper adminMapper; } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值