爱游戏全站app官网入口-爱游戏官网

springmvc spring mybatis 基于注解整合 -爱游戏全站app官网入口

2023-08-21,,

最近在给学生们讲spring mybatis整合,根据有的学生反映还是基于注解实现整合便于理解,毕竟在先前的工作中团队里还没有人完全舍弃配置文件进行项目开发,由于这两个原因,我索性参考spring官方文档研究出完全基于注解整合ssm框架。毕竟无配置化也是spring官方所推行的,要不springboot存在的意义为何嘛

  1)目标:毫无保留的将配置文件的所有配置项改变注解加创建对象的方式实现

2)spring提供的 @bean @configuration @componentscan @enabletransactionmanagement @enablewebmvc 等 需要知道其含义

  1) 项目结构目录:

  在这里web.xml里不写任何配置

  1. appconfig.java

package com.bdqn.lyrk.ssm.study.app;
import com.alibaba.druid.pool.druiddatasource;
import org.mybatis.spring.sqlsessionfactorybean;
import org.mybatis.spring.annotation.mapperscan;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.componentscan;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.propertysource;
import org.springframework.context.support.propertysourcesplaceholderconfigurer;
import org.springframework.core.io.support.pathmatchingresourcepatternresolver;
import org.springframework.jdbc.datasource.datasourcetransactionmanager;
import org.springframework.transaction.platformtransactionmanager;
import org.springframework.transaction.annotation.enabletransactionmanagement; import javax.sql.datasource;
import java.io.ioexception; /**
* spring的配置类
*
* @author chen.nie
* @date 2018/6/24
**/
@configuration //表明此类是配置类
@componentscan // 扫描自定义的组件(repository service component controller)
@propertysource("classpath:application.properties") // 读取application.properties
@mapperscan("com.bdqn.lyrk.ssm.study.app.mapper") //扫描mybatis的mapper接口
@enabletransactionmanagement //开启事务管理
public class appconfig { /**
* 配置数据源
*
* @date 2018/6/24
**/
@bean
public datasource datasource(propertiesconfig propertiesconfig) {
druiddatasource datasource = new druiddatasource();
datasource.setusername(propertiesconfig.getusername());
datasource.setpassword(propertiesconfig.getpassword());
datasource.set;
datasource.setdriverclassname(propertiesconfig.getdriverclass());
return datasource;
} /**
* 配置mybatis的sqlsessionfactorybean
*
* @param datasource
* @param propertiesconfig
* @return
*/
@bean
public sqlsessionfactorybean sqlsessionfactorybean(datasource datasource, propertiesconfig propertiesconfig) throws ioexception {
sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();
sqlsessionfactorybean.setdatasource(datasource);
sqlsessionfactorybean.settypealiasespackage(propertiesconfig.getmybatistypealiaspackages());
// 动态获取sqlmapper
pathmatchingresourcepatternresolver classpathresource = new pathmatchingresourcepatternresolver();
sqlsessionfactorybean.setmapperlocations(classpathresource.getresources(propertiesconfig.getmapperlocations())); return sqlsessionfactorybean;
} /**
* 配置spring的声明式事务
*
* @return
*/ @bean
public platformtransactionmanager transactionmanager(datasource datasource) {
datasourcetransactionmanager datasourcetransactionmanager = new datasourcetransactionmanager(datasource);
return datasourcetransactionmanager; } @bean
public static propertysourcesplaceholderconfigurer propertysourcesplaceholderconfigurer() {
propertysourcesplaceholderconfigurer propertysourcesplaceholderconfigurer = new propertysourcesplaceholderconfigurer();
return propertysourcesplaceholderconfigurer;
} }

没什么好说的,这里主要创建spring与mybatis整合的相关对象以及声明式事务切面,我们把配置文件中的东西通通用java代码创建,注意@bean注解的使用

  2.dispatcherconfig

 package com.bdqn.lyrk.ssm.study.config;
 import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.enablewebmvc;
import org.springframework.web.servlet.config.annotation.interceptorregistry;
import org.springframework.web.servlet.config.annotation.resourcehandlerregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;
import org.springframework.web.servlet.handler.simplemappingexceptionresolver;
import org.springframework.web.servlet.view.internalresourceviewresolver;
import org.springframework.web.servlet.view.jstlview; import java.util.properties; @configuration
@enablewebmvc
public class dispatcherconfig extends webmvcconfigureradapter { @autowired
private propertyconfig propertyconfig; @bean
public internalresourceviewresolver internalresourceviewresolver() {
internalresourceviewresolver internalresourceviewresolver = new internalresourceviewresolver();
internalresourceviewresolver.setviewclass(jstlview.class);
internalresourceviewresolver.setprefix(propertyconfig.getwebviewprefix());
internalresourceviewresolver.setsuffix(propertyconfig.getwebviewsuffix());
return internalresourceviewresolver;
} /**
* 设置统一错误处理要跳转的视图
*
* @return
*/
@bean
public simplemappingexceptionresolver simplemappingexceptionresolver() {
simplemappingexceptionresolver simplemappingexceptionresolver = new simplemappingexceptionresolver();
properties properties = new properties();
properties.getproperty("java.lang.exception", "error");
simplemappingexceptionresolver.setexceptionmappings(properties);
return simplemappingexceptionresolver;
} /**
* 添加静态资源
*
* @param registry
*/
@override
public void addresourcehandlers(resourcehandlerregistry registry) {
registry.addresourcehandler(propertyconfig.getwebstatichandler()).addresourcelocations(propertyconfig.getwebstaticresource()).setcacheperiod(propertyconfig.getwebstaticcachedperiod());
} /**
* 添加拦截器
*
* @param registry
*/
@override
public void addinterceptors(interceptorregistry registry) {
super.addinterceptors(registry);
}
}

  此处配置springmvc的视图解析器,静态资源等,依旧照搬配置文件中的代码

  3.propertiesconfig

package com.bdqn.lyrk.ssm.study.config;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.propertysource;
import org.springframework.context.support.propertysourcesplaceholderconfigurer; @configuration
@propertysource("classpath:application.properties")
public class propertyconfig { @value("${spring.datasource.url}")
private string url;
@value("${spring.datasource.driver}")
private string driver;
@value("${spring.datasource.user}")
private string user;
@value("${spring.datasource.password}")
private string password;
@value("${spring.web.view.prefix}")
private string webviewprefix;
@value("${spring.web.view.suffix}")
private string webviewsuffix;
@value("${spring.web.static.handler}")
private string webstatichandler;
@value("${spring.web.static.resource}")
private string webstaticresource;
@value("${spring.web.static.cache.period}")
private integer webstaticcachedperiod;
@value("${mybatis.type.alias.package}")
private string mybatistypealiaspackage; public string getwebviewprefix() {
return webviewprefix;
} public string getwebviewsuffix() {
return webviewsuffix;
} public string getwebstatichandler() {
return webstatichandler;
} public string getwebstaticresource() {
return webstaticresource;
} public integer getwebstaticcachedperiod() {
return webstaticcachedperiod;
} public string getmybatistypealiaspackage() {
return mybatistypealiaspackage;
} public string get {
return url;
} public string getdriver() {
return driver;
} public string getuser() {
return user;
} public string getpassword() {
return password;
} @bean
public static propertysourcesplaceholderconfigurer propertysourcesplaceholderconfigurer() {
return new propertysourcesplaceholderconfigurer();
}
}

 此处用于读取application.properties的文件内容 注意@value与@propertysource的含义

4.mywebappinitializer

 package com.bdqn.lyrk.ssm.study.config;
 import org.springframework.web.filter.characterencodingfilter;
import org.springframework.web.servlet.dispatcherservlet;
import org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer; import javax.servlet.filter;
import javax.servlet.servletcontext;
import javax.servlet.servletexception; /**
* 初始化servlet webapplicationcontext 相关
*
* @author chen.nie
* @date 2017/12/28
**/
public class mywebappinitializer extends abstractannotationconfigdispatcherservletinitializer { @override
protected class[] getrootconfigclasses() {
return new class[]{appconfig.class};
} @override
protected class[] getservletconfigclasses() {
return new class[]{dispatcherservlet.class};
} @override
protected string[] getservletmappings() {
return new string[]{"/"};
} /**
* 添加过滤器
*
* @return
*/
@override
protected filter[] getservletfilters() {
characterencodingfilter characterencodingfilter = new characterencodingfilter();
characterencodingfilter.setencoding("utf-8");
characterencodingfilter.setforceencoding(true);
return new filter[]{characterencodingfilter};
}
}

  在这里请大家关注一下这个类,这段代码的含义和配置springmvc的含义一样:

 

contextconfiglocation
/web-inf/root-context.xml


dispatcher
org.springframework.web.servlet.dispatcherservlet

contextconfiglocation


1


dispatcher
/


org.springframework.web.context.contextloaderlistener

  5. application.properties

#数据库连接
spring.datasource.user=root
spring.datasource.password=root
spring.datasource.driver=com.mysql.jdbc.driver
spring.datasource.url=jdbc:mysql://localhost:3306/myschool?characterencoding=utf-8&usessl=false
#web设置相关
spring.web.view.prefix=/web-inf/jsp/
spring.web.view.suffix=.jsp
spring.web.static.handler=/assets/**
spring.web.static.resource=classpath:/assets/
spring.web.static.cache.period=360000
#mybatis设置相关
mybatis.type.alias.package=com.bdqn.lyrk.ssm.study.entity

6.创建mybatis对应的mapper

package com.bdqn.lyrk.ssm.study.mapper;
import com.bdqn.lyrk.ssm.study.entity.studententity;
import org.apache.ibatis.annotations.select; import java.util.list; public interface studentmapper { @select("select * from student")
list selectall();
}

7.创建业务逻辑

 package com.bdqn.lyrk.ssm.study.service.impl;
 import com.bdqn.lyrk.ssm.study.entity.studententity;
import com.bdqn.lyrk.ssm.study.mapper.studentmapper;
import com.bdqn.lyrk.ssm.study.service.istudentservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional; import java.util.list; @service
public class studentserviceimpl implements istudentservice {
@autowired
private studentmapper studentmapper; @override
public list selectall() {
return studentmapper.selectall();
} @transactional
@override
public int save(studententity studententity) {
return 0;
} }

 8.创建controller

package com.bdqn.lyrk.ssm.study.controller;
import com.bdqn.lyrk.ssm.study.entity.studententity;
import com.bdqn.lyrk.ssm.study.service.istudentservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.ui.modelmap;
import org.springframework.web.bind.annotation.getmapping; import java.util.list; @controller
public class indexcontroller {
@autowired
private istudentservice studentservice; @getmapping("/index")
public string index(modelmap modelmap) {
list list = studentservice.selectall();
modelmap.put("students", list);
return "index";
}
}

9.index.jsp文件中内容

<%--
created by intellij idea.
user: chen.nie
date: 2017/12/23
time: 下午8:40
to change this template use file | settings | file templates.
--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


$title$



${student.stuname}


10.启动tomcat后访问http://localhost:8080/portal/index得到如下界面

ok!大功告成,注意前4步里面注解的运用,后面的步骤和往常的写法无异,想必大家都很熟悉了吧。

springmvc spring mybatis 基于注解整合的相关教程结束。

网站地图