spring可以通过两种方式进行注入,注入就可使用一下两种方式进行调用bean
方式一:这是xml形式的: static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); 方式二:ctx=new AnnotationConfigApplicationContext(MybatisConfig.class);然后两种方式都可以通过getbean()调用其中的bean,用于spring是单例的,这就避免了创建对象节省了内存。
spring的配置方法也有两种,一种是spring的xml,一种是注解。 以下是xml配置:
<?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd"> 加载类路径下的Jdbc配置文件 9 <context:property-placeholder location="classpath:Jdbc.properties"></context:property-placeholder> 10 配置Dbcp数据源 11 <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> 12 <property name="driverClassName" value="${jdbc.driver}"></property> 13 <property name="url" value="${jdbc.uri}"></property> 14 <property name="username" value="${jdbc.name}"></property> 15 <property name="password" value="${jdbc.pwd}"></property> 16 </bean> 17 //配置SqlsessionFactory用来创建Sqlsession 18 <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 19 <property name="dataSource" ref="dataSource"></property> 对该包下的实体类起别名 不需要用全类名的方法要标记 20 <property name="typeAliasesPackage" value="com.entity"></property> 扫描对应的Mapper.xml 需要引入的Mapper.Xml 21 <property name="mapperLocations"> 22 <list> 23 <value>classpath*:com/mapper/UserMapper.xml</value> 24 </list> 25 </property> 26 </bean> 27 //配置Mapper扫描,对指定mAooer包下的的Mapper生成对应的实现,并且注入Spring容器,与之对应的就是在@configuration上面添加@MapperScan 28 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 29 <property name="basePackage" value="com.mapper"></property> 30 </bean> 31 32 </beans>以下是注解方式:
package ssm.config; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; 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.core.io.Resource; import javax.sql.DataSource; @Configuration @PropertySource("classpath:jdbc.properties") @MapperScan(basePackages = "ssm.mapper") public class MybatisConfig { @Bean public DataSource dataSource( @Value("${db.driver}")String driver, @Value("${db.url}")String url, @Value("${db.username}")String username, @Value("${db.password}")String password, @Value("${db.maxActive}")int maxActive, @Value("${db.initialSize}")int initialSize ){ DruidDataSource ds=new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); ds.setInitialSize(initialSize); ds.setMaxActive(maxActive); return ds; } @Bean public SqlSessionFactory ssf(DataSource dataSource, @Value("${mybatis.mapper.location}") Resource[] mapperLocation) throws Exception { SqlSessionFactoryBean bean=new SqlSessionFactoryBean(); //给bean设置数据源 bean.setDataSource(dataSource); bean.setMapperLocations(mapperLocation);//这里设置了mapper.xml的路径 return bean.getObject(); } }SqlSessionFactory(一个数据库有一个SqlSessionFactory,因为来自配置的url)是连接数据库的关键,通过sqlSessionFactory创建SqlSession,SQLSession里面又很多封装的方法,比如:
SqlSession sqlSession = this.sqlSessionFactory.openSession(); int result = sqlSession.insert("com.javacode2018.chat02.UserMapper.insertUser", userModel); //insertUser是对应usermapper接口里面的方法,后面通过usermapper.xml进行实现 UserMapper mapper = sqlSession.getMapper(UserMapper.class);//使用接口方法 //最后将mapper接口通过mapperscan注入spring,实现 ctx=new AnnotationConfigApplicationContext(MybatisConfig.class); UserMapper user=ctx.getbean("userMapper",UserMapper.class);以上就是Spring与MyBatis整合
Mybatis个人配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 环境配置,可以配置多个环境 --> <environments default="chat03"> <!-- environment用来对某个环境进行配置 id:环境标识,唯一 --> <environment id="chat03"> <!-- 事务管理器工厂配置 --> <transactionManager type="org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory"/> <!-- 数据源工厂配置,使用工厂来创建数据源 --> <dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/javacode2018?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root123"/> </dataSource> </environment> </environments> </configuration> String resource = "mybatis-config.xml"; //读取全局配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); //构建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);需导入spring—webmvc,
jstl包,jstl用来写${}方便的
然后就是在web.xml里面配置,再将配置的好的mvc配置文件,在web.xml里面初始化,麻烦,不详细解释了。
以下是简单地注解配置:
① 首先需要继承一个类
package mvc.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.Filter; public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { System.out.println("111111111111111111111111"); //返回mvc的配置类 return new Class[]{ MvcConfig.class,InterceptorConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { System.out.println("2222222222222222222"); return new Class[0]; } @Override protected String[] getServletMappings() { System.out.println("33333333333333333"); //用来设置对于那些做出相应 return new String[]{"*.do"}; } //配置防止中文乱码 @Override protected Filter[] getServletFilters() { return new Filter[]{new CharacterEncodingFilter("utf-8")}; } } package mvc.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration @ComponentScan(basePackages = "mvc.controller") //表示这个配置类作用域mvc @EnableWebMvc public class MvcConfig { @Bean public ThymeleafViewResolver viewResolver(){ System.out.println("init ThymeleafViewResolver"); //设置模板保存位置为 /resources/templates/*.html ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); //模版存储文件夹 templateResolver.setPrefix("/templates/"); //模版后缀 templateResolver.setSuffix(".html"); templateResolver.setCharacterEncoding("UTF-8"); templateResolver.setTemplateMode(TemplateMode.HTML); templateResolver.setCacheable(true); //创建模板引擎 SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); templateEngine.setEnableSpringELCompiler(true); //创建模版解析器 ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setCharacterEncoding("UTF-8"); viewResolver.setTemplateEngine(templateEngine); return viewResolver; } }5 Spring Boot
springBoot就是将配置简化,通过properties里面将各种数据输入,配置连接池 然后通过自动装配即可。