JAVASpring

Spring的@Repository注解与 Mybatis的@Mapper以及@MapperScan注解的区别

@Repository


@Repository 是 Spring 的注解,用于声明一个 Bean,主要用于声明dao层的bean,这种方式是基于代码的开发,也就是手写jdbc。(这个注解和@Service,@Controller一样)

样例:

@Repository
public class UserDaoImpl implements UserDao{
	
	@Override
	public int insertUser(){
		JdbcTemplate template = new JdbcTemplate();
		...
	}
}

@Mapper


@Mapper 注解是mybatis的一个注解,与spring没有关系,是mybais基于注解开发的一种方式,这种方式就需要写xml文件了。

样例:

@Repository // 也可以使用@Component,效果都是一样的,只是为了声明为bean
@Mapper // 加了这个注解会自动帮我们实现一个该接口的代理类
public interface UserDao {
	@Insert("insert into user(account, password, user_name) " +
            "values(#{user.account}, #{user.password}, #{user.name})") //使用注解的方式写sql语句
    int insertUser(@Param("user") User user) throws RuntimeException;
}

@MapperScan


这个注解是扫描某个包,自动为这个包下的接口自动实现接口实现类。

样例:

@MapperScan("com.chen.gulimall.product.dao")
@SpringBootApplication
public class MallProductApplication {

	public static void main(String[] args) {
		SpringApplication.run(MallProductApplication.class, args);
	}

}

总结


  • 1.@MapperScan是要spring启动时,扫描到所有的Mapper文件,并生成代理类交给spring容器管理;
  • 2.@Mapper注解,当项目启动时,扫描到被此注解标识接口类,就会创建代理类并交给spring容器管理。
  • 3.如果不加@MapperScan注解,那么Mapper接口类上就要添加@Mapper注解。
  • 4. @Repository注解是spring的注解,主动标识当前类要交给spring容器管理(相当于@Component注解)。
  • 5.一般添加了@Mapper注解或者@MapperScan注解,那么就不用添加@Repository。因为@Mapper注解(@MapperScan注解)已将改接口的代理类给了spring容器管理。但是,有时候IDEA会识别不了@Mapper注解,在项目自动编译的时候,项目会爆红色波浪线,加@Respository注解,可以抑制这种报错。