@Autowired – 空指针

huangapple go评论76阅读模式
英文:

Autowired - null pointer

问题

我正在尝试通过一些非常基本的示例来理解Autowired的工作原理... 当涉及到典型的控制器/服务/数据访问对象时,它按预期工作,但是当我想创建其他东西时,我一直在努力处理某些空指针问题...

我有两个类:Car(汽车)、Engine(引擎)以及一个启动类。

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @Component
    public class Car {
        private int power;
        @Autowired
        Engine engine;

        public String showEngineName() {
            return engine.getName();
        }
    }
    
    @Getter
    @Setter
    @Component
    public class Engine {
        private String name = "超级引擎";
    
        public String getName() {
            return name;
        }
    }


    @SpringBootApplication
    public class EduApplication {
    
        public static void main(String[] args) {
            Car car = new Car();
            String engineName = car.showEngineName();
            System.out.println(engineName);
            SpringApplication.run(EduApplication.class, args);
    
        }
    
    }

当我启动应用程序时,汽车被初始化,但其中的引擎为空...
有人能解释一下为什么吗?难道不应该有一个引擎,其名称为"超级引擎"吗?

谢谢!

英文:

I am trying to understand how the Autowired works with really basic examples... when it comes to typical controller/service/dao it works as expected but when I wanted to create sth else I've been struggling with some NullPointers...

I have two classes: Car, Engine and starting one.

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @Component
    public class Car {
        private int power;
        @Autowired
        Engine engine;

        public String showEngineName() {
            return engine.getName();
        }
    }
    
    @Getter
    @Setter
    @Component
    public class Engine {
        private String name = "super engine";
    
        public String getName() {
            return name;
        }
    }


    @SpringBootApplication
    public class EduApplication {
    
        public static void main(String[] args) {
            Car car = new Car();
            String engineName = car.showEngineName();
            System.out.println(engineName);
            SpringApplication.run(EduApplication.class, args);
    
        }
    
    }

When I start the application, the car is initialized but the engine inside is null...
Can someone explain to me why? Shouldn't be there an engine with name, super engine''?

Regards!

答案1

得分: 4

你得到了NullPointerException,因为你引用了由你显式创建而不是由Spring创建的Car实例,因此在该对象上没有执行依赖注入,engine字段保持为null。

英文:

You get NullPointerException because you referring to Car instance that was created explicitly by you and not by Spring, therefore no dependency injection was perform on this object and engine field stayed null.

huangapple
  • 本文由 发表于 2020年9月28日 01:35:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64091407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定