1.纯注解开发【定义配置类的注解】
==@Confituration == 表示该类是一个配置类
==@ComponentScan(“com.itheima”) == 配置包扫描
@PropertySource(“classpath:jdbc.properties”) 加载属性文件
==@Import(JdbcConfig.class) == 加载其他配置类
2.spring整合mybatis【纯注解,3个配置类】
<1>SpringConfig配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;@Configuration //表示该类是一个配置类,用来代替applicationContext.xml,这个注解可以不写,但是一般都写了
//<context:component-scan base-package="com.itheima"/>
@ComponentScan("com.itheima") //Spring包扫描
//<context:property-placeholder location="classpath*:*.properties"/>
@PropertySource("classpath:jdbc.properties") //加载属性文件
// <import resource="classpath:applicationContext-dao.xml"/>
@Import(JdbcConfig.class) //引入分配置类
public class SpringConfig {
}
<2>JdbcConfig配置类
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String driverClassName;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource() {DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driverClassName);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}
}
<3>MybatisConfig 配置
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;public class MybatisConfig {@Beanpublic SqlSessionFactoryBean SqlSessionFactoryBean(@Autowired DataSource dataSource){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();//1.注入连接池对象【必须】ssfb.setDataSource(dataSource);//2.加载MybatisConfig.xml核心配置文件,// 如果核心配置文件中的内容都被抽取了,那么就可以不用加载【可选】//ClassPathResource resource = new ClassPathResource("classpath:MybatisConfig.xml");//ssfb.setConfigLocation(resource);//3 配置别名,如果是使用注解配置SQL语句,可以不用配置别名【可选】//ssfb.setTypeAliasesPackage("com.itheima.bean");//4 加载映射配置文件,如果映射配置文件和mapper接口在同一个包下,并且同名,那么会自动加载【可选】//ClassPathResource resource = new ClassPathResource("classpath:StudentMapper.xml");//ssfb.setMapperLocations(resource);return ssfb;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.mapper");return msc;}
}
3.具体实现类及测试类
<1>StudentServiceImpl类:
package com.itheima.service.impl;import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.util.List;@Service("studentService")
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper mapper;//注入StudentMapper的代理对象@Overridepublic List<Student> selectAll() throws IOException {return mapper.selectAll();}@Overridepublic Student selectById(Integer id) throws IOException {return mapper.selectById(id);}@Overridepublic Integer insert(Student stu) throws IOException {return mapper.insert(stu);}@Overridepublic Integer update(Student stu) throws IOException {return mapper.update(stu);}@Overridepublic Integer delete(Integer id) throws IOException {return mapper.delete(id);}
}
<2>studentMapper类
package com.itheima.mapper;
import com.itheima.bean.Student;
import org.apache.ibatis.annotations.*;import java.util.List;
public interface StudentMapper {//查询全部@Select("select * from student")public abstract List<Student> selectAll();//根据id查询@Select("select * from student where id=#{ID}")public abstract Student selectById(Integer id);//新增数据@Insert("insert into student values(null,#{name},#{age})")public abstract Integer insert(Student stu);//修改数据@Update("update student set name=#{name},age=#{age} where id=#{id}")public abstract Integer update(Student stu);//删除数据@Delete(" delete from student where id=#{id}")public abstract Integer delete(Integer id);
}
<3>jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
#不加Jdbc系统会默认username为系统用户名
jdbc.username=root
jdbc.password=123456
❤️-4>测试类:
获取容器方式为加载配置类:
@Testpublic void test1() throws IOException {//从美IOC中取studentService对象//ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);StudentService studentService = applicationContext.getBean("studentService", StudentService.class);List<Student> list = studentService.selectAll();list.forEach(stu-> System.out.println(stu));}打印结果:
---------------------------------------------------------------------
Student{id=1, name='张三', age=23}
Student{id=2, name='李四', age=24}
Student{id=15, name='小郭', age=22}
4.spring整合junit单元测试
前提:添加spring-test和junit依赖,并且junit依赖的版本必须大于等于4.12版本。
【第一步】
<!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--Spring整合junit单元测试--><!--junit的依赖至少要是4.12版本,可以是4.13等版本,否则出现如下异常--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version></dependency>
【第二步】
spring的Junit测试类整合
import com.itheima.bean.Student;
import com.itheima.config.SpringConfig;
import com.itheima.service.StudentService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.io.IOException;
import java.util.List;//【第二步】使用spring中提供的单元测试运行类替换JVM中单元测试运行类
@RunWith(SpringJUnit4ClassRunner.class)
//【第三步】加载配置文件或者配置类[将bean对象注入容器]
@ContextConfiguration(classes = {SpringConfig.class})
public class StudentJunit {@Autowired//[将studentService采用set注入方式,则不能new容器对象获取]private StudentService studentService;@Testpublic void test1() throws IOException {List<Student> list = studentService.selectAll();//断言测试,与预期一致则通过,反正爆出不同的地方Assert.assertEquals(24,list.size());}@Testpublic void test2() throws IOException {Student stu = studentService.selectById(20);Assert.assertEquals("陈锦涛",stu.getName());}
}