SpringCore
01|Spring Bean 定义常见错误
案例 1:隐式扫描不到 Bean 的定义
案例 2:定义的 Bean 缺少隐式依赖
案例 3:原型 Bean 被固定
02|Spring Bean 依赖注入常见错误(上下)
案例 1:过多赠予,无所适从 (我们仅需要一个 Bean,但实际却提供了 2 个)
案例 2:显式引用 Bean 时首字母忽略大小写
案例 3:引用内部类的 Bean 遗忘类名
匿名内部类的注入
@Autowired
@Qualifier("studentController.InnerClassDataService")
DataService innerClassDataService;
案例 1:@Value 没有注入预期的值
案例 2:错乱的注入集合 \
04|Spring Bean 生命周期常见错误
案例 1:构造器内抛空指针异常 \
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class LightMgrService {
@Autowired
private LightService lightService;
public LightMgrService() {
lightService.check();
}
}
@Service
public class LightService {
public void start() {
System.out.println("turn on all lights");
}
public void shutdown() {
System.out.println("turn off all lights");
}
public void check() {
System.out.println("check all lights");
}
}
空指针错误:使用 @Autowired 直接标记在成员属性上而引发的装配行为是发生在构造器执行之后的
问题修正:
@Component
public class LightMgrService {
private LightService lightService;
public LightMgrService(LightService lightService) {
this.lightService = lightService;
lightService.check();
}
}
案例 2:意外触发 shutdown 方法 \