@Mapper和@Repository是常用的兩個注解,兩者都是用在dao上,兩者功能差不多,容易混淆,有必要清楚其細微區別;
區別:
@Repository需要在Spring中配置掃描地址,然后生成Dao層的Bean才能被注入到Service層中:如下,在啟動類中配置掃描地址:
@SpringBootApplication //添加啟動類注解 @MapperScan("com.xz.springboot.mapper") //配置mapper掃描地址 public class application { public static void main(String[] args) { SpringApplication.run(application.class,args); } }
@Mapper不需要配置掃描地址,通過xml里面的namespace里面的接口地址,生成了Bean后注入到Service層中。
也就是@Repository多了一個配置掃描地址的步驟;
補充:
如果在接口上@Mapper,然后再在 xml中的namespace指向mapper,那么spring就能動態生成一個Mapper的bean,然后你在serviceImpl中的
@Autowired
pravate XXXMapper xxmapper;
就會被這個bean注進去。
如果在DaoImpl中加了@Repository,那么在spring的掃包機制下,也會生成這個dao的bean,注入你serviceImpl中的
@Autowired
private xxxDao xxxdao;
中去。這個機制就像@controller,@Service什么的一樣的。
最后,一般不用@Repository,在spring boot中通常用@Mapper