@Autowired是从IOC容器中获取已经初始化的对象,此对象中@Autowired的属性也已经通过容器完成了注入,整个生命周期都交由容器管控。然而通过new出来的对象,生命周期不受容器管控,自然也无法完成属性的自动注入。
@Autowired相当于setter,在注入之前,对象已经实例化,是在这个接口注解的时候实例化的;
而new只是实例化一个对象,而且new的对象不能调用注入的其他类
eg:
1、控制器
@controller
public class BusinessShopShoesController extends BaseController {
@Autowired
private ShoesService shoesService;//相当于setter,已经实例化
}
1
2
3
4
5
6
2、业务层
@service
public class ShoesService extends CrudService<ShoesDao, Shoes> {
@Autowired
ShoesModelDao shoesModelDao;
@Transactional(readOnly = false)
public Shoes get(int id)
{
return shoesModelDao.get(id);
}
}
1
2
3
4
5
6
7
8
9
10
11
此时如果1 中new一个service,那么就不能调用2 中的Dao了,因为DAO是依赖注入的
转载:https://blog.csdn.net/p358278505/article/details/78404828