spring中有三种Bean注入方式
1.注解注入@Autowired
该注入方式在项目中使用较多,但需要考虑空指针异常(NPE)的出现
//例子
public class Phone {
@Autowired
private Camera camera;
public String cameraBrand(){
return this.camera.getBrand();
}
}
//测试代码
new Phone().cameraBrand();//出现NullPointException
2.setter注入
private Fruit fruit;
@Autowired //定义在set方法上
public void setUserDao(Fruit fruit) {
this.fruit = fruit;
}
3.构造函数注入(推荐使用)
@RestController
public class TestController {
private final Integer test_id;
public TestController(Integer test_id) {
this.test_id = test_id;
}
}
值得注意的是当类只有一个构造器时,可以不用把@Autowired注明在构造器或者构造器参数上
暑期编程PK赛
得CSDN机械键盘等精美礼品!