英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论