@MapperScan注入的bean与普通bean区别
时间: 2023-03-06 14:22:05 浏览: 80
在Spring中,@MapperScan是用来扫描MyBatis映射器接口并将其注入到Spring容器中的注解。与普通的bean相比,由@MapperScan注入的bean具有以下几个区别:
1. 使用@MapperScan注解时,会扫描指定的包路径下的MyBatis映射器接口,并将这些接口实例化成bean并注册到Spring容器中。
2. 由于@MapperScan注解是MyBatis框架提供的,因此在使用时需要引入MyBatis依赖。
3. 由于@MapperScan注解是为了将MyBatis映射器接口注入到Spring容器中,因此这些bean一般是用来执行数据库操作的。
4. 与普通bean相比,由@MapperScan注入的bean具有更多的MyBatis特性,例如事务控制、缓存等。
相关问题
@componentscan和@mapperscan区别
@componentscan和@mapperscan是Spring Boot中的注解。
@componentscan扫描并注册了被@Component、@Repository、@Service、@Controller、@Configuration等注解标识的类,将其放入Spring上下文中,方便其他组件进行调用。
@mapperscan是MyBatis框架中的注解,用于扫描Mapper接口所在的包,并将其注册到MyBatis中,让Mapper接口能够被注入到其他组件中进行调用。
区别在于,@componentscan主要是扫描和注册Spring的Bean,而@mapperscan主要是扫描和注册Mapper接口,两者作用不同,但都是为了提高组件的可用性。
@MapperScan注解
@MapperScan是MyBatis框架中的注解,用于扫描MyBatis Mapper接口并将其注册到Spring容器中。在使用MyBatis时,通常需要定义Mapper接口来映射SQL语句,@MapperScan注解可以让Spring自动扫描这些Mapper接口并将其实例化,从而可以在代码中方便地使用这些Mapper接口。
@MapperScan注解有以下两个常用属性:
- basePackages:指定Mapper接口所在的包路径,可以使用通配符。
- sqlSessionTemplateRef:指定SqlSessionTemplate的bean名称,用于执行Mapper接口中的SQL语句。
示例代码如下:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(@Autowired DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(@Autowired SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
```
在上面的代码中,@MapperScan注解用于扫描com.example.mapper包下的Mapper接口,并将其注册到Spring容器中,同时指定了SqlSessionTemplate的bean名称为sqlSessionTemplate。这样,在Mapper接口中就可以使用@Autowired注解自动注入SqlSessionTemplate并执行SQL语句了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)