spring boot @Autowired 练习问题记录
报错:
现在提示:
Exception in thread "main" java.lang.NullPointerException
at test1206.BussinessPerson.service(BussinessPerson.java:12)
at test1206.App1206.main(App1206.java:6)
Process finished with exit code 1
以下是部分代码;
package test1206;
public class App1206 {
public static void main(String[] args) {
BussinessPerson bussinessPerson=new BussinessPerson();
bussinessPerson.service();
}
}
package test1206;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BussinessPerson implements Person{
@Autowired
private Animal animal = null;
@Override
public void service() {
this.animal.use();
}
@Override
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
package test1206;
public class Dog implements Animal{
@Override
public void use() {
System.out.println("狗会叫"+Dog.class.getSimpleName()+"会看门!!");
}
}
解决方案:
从报错信息和代码中可以看出,NullPointerException 是由于 animal 为 null 时调用了 animal.use() 引起的。具体原因及解决办法如下:
1. 问题分析
-
原因:
- Spring 的
@Autowired注解用于自动注入依赖对象。 - 当前代码中,
BussinessPerson的animal属性标注了@Autowired,但在App1206的main方法中,没有通过 Spring 容器获取BussinessPerson实例,而是直接使用new创建的对象。 - 因为
new BussinessPerson()创建的对象未被 Spring 管理,因此@Autowired无效,animal属性保持为null。
- Spring 的
-
核心问题:
BussinessPerson未被 Spring 容器管理。
2. 解决办法
方法一:使用 Spring 容器管理对象
将 App1206 类改为通过 Spring 容器获取 BussinessPerson 的 Bean:
修改后的代码:
package test1206;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App1206 {
public static void main(String[] args) {
// 初始化 Spring 容器
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// 从容器中获取 BussinessPerson Bean
BussinessPerson bussinessPerson = context.getBean(BussinessPerson.class);
bussinessPerson.service();
}
}
同时需要配置 Spring 容器,例如创建一个配置类 AppConfig:
package test1206;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("test1206") // 指定扫描的包
public class AppConfig {
}
方法二:手动设置依赖(不推荐)
如果不使用 Spring 容器,可以手动为 animal 属性赋值:
修改 App1206 的代码:
package test1206;
public class App1206 {
public static void main(String[] args) {
BussinessPerson bussinessPerson = new BussinessPerson();
Animal dog = new Dog();
bussinessPerson.setAnimal(dog); // 手动注入依赖
bussinessPerson.service();
}
}
3. 推荐方案
建议使用 方法一,即通过 Spring 容器管理 BussinessPerson,从容器中获取 Bean 进行操作。这样不仅符合 Spring 的设计理念,还能在实际开发中更方便地管理和扩展依赖关系。
4. 其他建议
-
检查
Animal的实现类是否被正确注册为 Bean: 确保Dog类上添加了@Component注解:@Component public class Dog implements Animal { @Override public void use() { System.out.println("狗会叫 " + Dog.class.getSimpleName() + " 会看门!!"); } } -
调试日志: 如果问题仍未解决,可启用 Spring 的调试日志,确认容器是否正确初始化了所有 Bean。

浙公网安备 33010602011771号