总体流程预览:
配置
导入文件
普通项目: database 配置 + DatasourceUtil 工具类 获取Connection
mybatis项目: mybatis-config 配置 + MybatisUtils工具类 获取 SqlSession
**Spring 项目:**applicationContext.xml + spring-config + mybatis-config2(复制过来,注释掉大部分,不影响原来项目代码的运行)
通过 spring 容器,自动注入 Mapper(@Autowired)或者直接 使用 AppConfig 配置类,自动注入 Mapper(@Autowired),两者等价。
修改配置文件中的 扫描路径:
修改数据源
修改 SqlSessionFactory 导入的资源 和 Mapper 映射文件
扫描 类(@Component 注册成bean) 和 扫描 接口(@Component (Dao层 @Repository)标记接口被 mybatis 接管)
注意:如果不使用 注解 标记 接口,能正常使用,但是 在 使用 @Autowired 自动注入接口 对应的 Mapper 时,插件因为会因为没识别到接口 而报错
注解形式
注解形式
看到这里应该明白刚才 帮 注解 @Repository(@Component) ,相当于做了什么工作了吧?
请将回答写在这里:
将 Spring 容器 注册到 web 项目中
有两种方式
方法一:在 web.xml 文件中配置 项目启动时 读取 Spring 容器
通过 读取 xml 文件 注册容器到 c
在 监听器 启动的时候,读取 spring 配置文件,初始化容器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
因为这里是 根路径(直接就在resources目录下) 所以就用了 classpath: 配置文件名.xml 。 这里是用了默认的 xml 容器。
读取配置类 , 注册容器到 ServletContext
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.vdp</param-value>
<!-- <param-value>/</param-value>-->
</context-param>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
这里第二个<context-param> 指定了 使用 Spring 的 AnnotationConfigWebApplicationContext 注解配置类Web配置类 支持。这样才支持把 @Configuration 注解配置类 读取 到Spring 指定的容器。如果没有这段代码,它默认使用 web xml 容器,应该是不支持 注解类的
第一个是指定包名进行 扫描,你可以扫描所有的包,也可以只扫描到一个 使用@ComponentScan(basePackages = “com.vdp”) 扫描了其它包的 注解配置类( @Configuration ),效果是一样的,都是指定扫描包,注册到bean。
上面就一个配置文件,而且在根目录,所以就不扫包了,直接写 配置文件名 即可。这里使用一个 / 居然能扫 项目中所有的 包,都没写通配符,关于怎么写路径,自己可以多多尝试。 包名虽然可以用 / ,但是规范点还是用 . 来分割 java 项目的 包 比较好
【推荐使用方法】
方法二:实现 spring(org.springframework.web) 包下的 接口 WebApplicationInitializer
public interface WebApplicationInitializer {
/**
* Configure the given {@link ServletContext} with any servlets, filters, listeners
* context-params and attributes necessary for initializing this web application. See
* examples {@linkplain WebApplicationInitializer above}.
* @param servletContext the {@code ServletContext} to initialize
* @throws ServletException if any call against the given {@code ServletContext}
* throws a {@code ServletException}
*/
void onStartup(ServletContext servletContext) throws ServletException;
}
如果你实现了这个 方法,Web项目在启动时,会先执行这个方法,可以在这个方法中把我们的 spring 容器,注入到 servletContext 中。
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("Tomcat启动了web项目");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
servletContext.setAttribute("context",context);
}
读取xml配置文件,或者读取注解类,得到我们的 Spring 容器 context, 再把 context 保存到 servletContext 里面,看得出这里使用的是Map键值对的方式保存,所以在使用时,需要记住你在这里 设置的 key
拓展:实现 servlet(javax.servlet) 包下的 接口 ServletContextListener
package javax.servlet;
import java.util.EventListener;
public interface ServletContextListener extends EventListener {
default void contextInitialized(ServletContextEvent sce) {
}
default void contextDestroyed(ServletContextEvent sce) {
}
}
这个接口 继承了 事务监听器 接口,所以在启动 Web项目时,也会被启动,它设置了默认的实现方法(空的),所以可以不实现它的方法。
可以看得出,这是在 Tomcat 服务器 启动 和 结束 时 分别 会 调用这两个方法。
所以我们只需要 继承这个接口,并且在实现 contextInitialized 方法就好了
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Tomcat启动了web项目");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
sce.getServletContext().setAttribute("context",context);
}
在 Servlet 中 通过 上下文对象(ServletContext) 获取 spring 容器
注意点:如果是通过上面的方式一(web.xml 方式注册的容器 ) 它set容器 到 ServletContext 的时候,使用的键是:
这是一个全限定类名
// "org.springframework.web.context.WebApplicationContext.ROOT"
你也可以通过 它的源代码去看,它里面有一个 default 的属性 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 也是这个值
// WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
注意:传进去的参数是一个字符串。是 Map 中的 KEY
【这是一张不重要的图】
修改Controller 中获取 Service 的方法
本来是通过无参构造方法,new 一个 Service对象 ,现在改为使用 容器 注入 @Autowired
修改 Service 中 获取 Mapper 的方式
普通项目获取dao 对象 ,调用dao层方法执行 sql 代码的方式
private RepairDao dao;
public RepairServiceOld() {
this.dao = new RepairDao();
}
mybatis项目 获取 SqlSession,再通过 Mapper 接口 执行 Mapper.xml 中的 sql 代码的方式
try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
RepairMapper mapper = sqlSession.getMapper(RepairMapper.class);
int repairListTotal = mapper.getRepairListTotal(req);
// 上面就是 获取 mapper 执行sql 代码 返回结果
repairListResp.setPageTotal(repairListTotal);
if( repairListTotal > 0 && repairListTotal >= startTotal ){
List<RespDate> repairList = mapper.getRepairList(req);
repairListResp.setData(repairList);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
使用 spring 注入直接获取到 Mapper 的方式 【看这里】
@Service
public class RepairService {
@Autowired
RepairMapper mapper;
然后就可以 修改我们的代码(把从对象工厂获取mapper的代码,直接改成 使用 mapper 就好了),把一个mybatis 项目整合成 spring-mybaits 项目了。