美文网首页
使用@Autowired自动装配对象和new对象的区别

使用@Autowired自动装配对象和new对象的区别

作者: 03ca2835cf70 | 来源:发表于2019-07-30 15:51 被阅读0次

@Autowired相当于setter,在注入之前,对象已经实例化,是在这个接口注解的时候实例化的;
而new只是实例化一个对象,而且new的对象不能调用注入的其他类
eg:
1、控制器

@controller
public class BusinessShopShoesController extends BaseController {
 
    @Autowired
    private ShoesService shoesService;//相当于setter,已经实例化
}

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 中new一个service,那么就不能调用2 中的Dao了,因为DAO是依赖注入的

相关文章

网友评论

      本文标题:使用@Autowired自动装配对象和new对象的区别

      本文链接:https://www.haomeiwen.com/subject/unynrctx.html