Spring中@Autowired直接属性注入对象为null是什么原因?
@Autowired字段注入为null的核心原因
按你贴出的代码,问题出在三处,按优先级排序:
- 最核心问题:
Main类未被Spring容器托管,且你没有正确启动Spring上下文。@Autowired的依赖注入逻辑仅对Spring容器创建、管理的Bean生效。你当前代码里:Main类没有加@Component等注解,不会被@ComponentScan扫描成为容器Bean;main方法中没有初始化Spring容器的逻辑(没有加载AppConfig配置创建应用上下文),你如果是直接手动newMain实例调用逻辑,Spring完全不会介入处理这个实例的字段赋值,interfacex自然保持默认值null。
修正后的启动代码参考:
// 给Main类加注解,让它能被扫描成容器Bean @Component public class Main { @Autowired Interfacex interfacex; public static void main(String args[]){ // 初始化Spring容器,加载配置类 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // 从容器中获取托管的Main实例,此时依赖已经完成注入 Main main = context.getBean(Main.class); // 正常调用即可 main.interfacex.doA(); context.close(); } } - 实现类存在语法错误,根本无法正常注册为Spring Bean:
- 接口名是
Interfacex(首字母大写I),你实现类声明时写的是implements interfacex(首字母小写i),Java是大小写敏感语言,这处错误会直接导致编译失败; - 接口中定义的方法默认是
public访问权限,你重写doA()时没有加public修饰符,使用了默认包级访问权限,违反Java重写规则(重写方法不能缩小父类/接口方法的访问范围),同样会导致编译失败或Spring动态代理创建Bean异常。
修正后的实现类代码:
@Component public class Interfaceximpl implements Interfacex { @Override public void doA(){ // 业务逻辑 } } - 接口名是
- 你当前的包扫描配置
@ComponentScan("com")本身没有问题,只要修复上面两处错误,路径完全可以覆盖com.a下的接口和com.b下的实现类,不需要额外调整扫描范围。
内容的提问来源于stack exchange,提问作者Plain_Dude_Sleeping_Alone
相关产品推荐
相关产品推荐

