0

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!

jnovack
  • 7,629
  • 2
  • 26
  • 40
Ernesto
  • 950
  • 1
  • 14
  • 31

1 Answers1

4

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.

Piotr Podraza
  • 1,941
  • 1
  • 15
  • 26
  • so how to create an object by spring? – Ernesto Sep 27 '20 at 17:55
  • Ok i created an object by .getBean(Car.class) but can you tell me if this is the only elegant way to create object by with spring? – Ernesto Sep 27 '20 at 18:01
  • 1
    You didn't create it, Spring did it. You instructed Spring to do so by annotating `Car` class with `@Component` annotation. You can access it with `getBean` method on `ApplicationContext` like you did or use `@Autowired` on a class field or method and it will result in Spring injecting this object for you. Both ways are equally correct and provide the exact same instance of `Car`. – Piotr Podraza Sep 27 '20 at 18:06