一、通过注解的方式实现自动装配
1、在需要自动生成和装配的类添加 注解
你的spring容器中要有一个 UserMapper接口类型的 Bean 不然自动装配 会报错
2、在spring配置文件 启用扫描注解
<!-- 需要在添加 xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd-->
<!-- 启用扫描注解 -->
<context:component-scan base-package="service"></context:component-scan>
3、在测试类
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService =(UserService) ac.getBean("userServiceImpl");
//这样就可以获取到 业务类接口的实例
二、通过 XML配置 的方式实现自动装配
1、Spring配置文件
<!-- 引入 数据库配置文件 -->
<!-- 创建数据源 -->
<!-- 配置 sqlsessionFactory -->
<!-- 配置自动生成Mapper接口对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper"></property>
</bean>
<!-- 使用xml配置 实现自动装填 -->
<bean id="userServiceImpl" class="service.UserServiceImpl" autowire="byType" ></bean>
<bean>节点的autowire属性实现了自动装配 autowire属性值共有4个
属性值 | 说明 |
---|---|
no | 不使用自动装配, Bena依赖关系必须通过property 元素定义 |
byType | 根据属性类型自动装配, 如果有多个与属性类型相同的Bean会抛出异常, 没有则不会设置属性 |
byName | 根据属性名自动装配, 找出容器中id与属性的setter方法匹配的Bean,找到则注入,否则什么都不做 |
constructor | 与byType的方式类型,不同之处在于它应用于构造器参数,如果没有找到于构造器参数类型一致的Bena,那么将会抛出异常 |