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

来源:互联网 发布:安卓生日祝福源码 编辑:程序博客网 时间:2024/06/18 09:42

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

@controllerpublic class BusinessShopShoesController extends BaseController {    @Autowired    private ShoesService shoesService;//相当于setter,已经实例化    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2、业务层

@servicepublic 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是依赖注入的

原创粉丝点击