一、基于XML
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring_ioc_xml</groupId>
<artifactId>zte</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--Dbutils依赖-->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<!--c3p0依赖-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
</dependencies>
</project>
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "studentServiceImpl" class="zte.com.business.service.StudentServiceImpl">
<!--这里采用构造注入的方式-->
<constructor-arg name="studentDao" ref = "studentDaoImpl"></constructor-arg>
</bean>
<bean id = "studentDaoImpl" class="zte.com.business.dao.StudentDaoImpl">
<!--这里采用set方法注入的方式-->
<property name="queryRunner" ref="runner"></property>
</bean>
<bean id = "runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--QueryRunner:带参构造,只能构造函数注入-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--链接数据库的信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://10.5.16.76:3306/stu_db"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
dao层(接口忽略)
package zte.com.business.dao;
public class StudentDaoImpl implements IStudentDao{
private QueryRunner queryRunner;
public void setQueryRunner(QueryRunner queyRunner) {
this.queryRunner = queryRunner;
}
public List<Student> findAllStudent() {
try{
List<Student> list = queryRunner.query("select * from student", new BeanListHandler<Student>(Student.class));
return list;
}catch (Exception e){
throw new RuntimeException("查询所有学生信息失败");
}
}
public Student findById(Integer studentId) {
try{
Student student = queryRunner.query("select * from student where id = ?", new BeanHandler<Student>(Student.class),studentId);
return student;
}catch (Exception e){
throw new RuntimeException("查询单个学生信息失败");
}
}
public void saveStudent(Student student) {
try{
queryRunner.update("insert into student (id,name) values (?,?)",student.getId(),student.getName());
}catch (Exception e){
throw new RuntimeException("添加单个学生信息失败");
}
}
public void deleteById(Integer studentId) {
try{
queryRunner.update("delete from student where id = ?",studentId);
}catch (Exception e){
throw new RuntimeException("删除单个学生信息失败");
}
}
}
service层(接口忽略)
package zte.com.business.service;
public class StudentServiceImpl implements IStudentService {
private IStudentDao studentDao;
public StudentServiceImpl(IStudentDao studentDao) {
this.studentDao = studentDao;
}
public List<Student> findAllStudent() {
return studentDao.findAllStudent();
}
public Student findById(Integer studentId) {
return studentDao.findById(studentId);
}
public void saveStudent(Student student) {
studentDao.saveStudent(student);
}
public void deleteById(Integer studentId) {
studentDao.deleteById(studentId);
}
}
测试类: 写在test包下
package com.test;
public class StudentTest {
/**
* 1. 应用程序的入口: main方法;
* 2,单元测试中,虽然没有main方法,但是junit实际集成了一个main方法; 如果加上@Test,则就会集成到;
* 3. junit根本不知道是否继承了spring框架,因此不会读取配置文件/配置类
*
* 由此可得:junit无法读取到容器,必须手动来创建容器,进行测试
*/
public static ApplicationContext ac;
public static IStudentService studentServiceImpl;
@Before
public void init(){
ac = new ClassPathXmlApplicationContext("bean.xml");
studentServiceImpl = (IStudentService) ac.getBean("studentServiceImpl");
}
@Test
public void find() {
List<Student> list = studentServiceImpl.findAllStudent();
System.out.println(list);
}
@Test
public void findById() {
Student student = studentServiceImpl.findById(2);
System.out.println(student);
}
@Test
public void deleteByid() {
studentServiceImpl.deleteById(5);
}
@Test
public void insertOne() {
Student student = new Student();
student.setId(5);
student.setName("zhang");
studentServiceImpl.saveStudent(student);
}
}
二、基于注解(XML转化为注解)
其他类
- service层,dao层代码根据之前经验修改即可,bean.xml删除;
jdbc.properties
driverClass=com.mysql.cj.jdbc.Driver
jdbcURL=jdbc:mysql://10.5.16.76:3306/stu_db
user=root
password=1234
副配置类
package zte.com.business.config;
/**1. 包扫描:必须先扫到带spring注解的类,再去扫描类中的其他注解
* 2. 副配置类:
* 1. 加@Configuration注解;
* 2. 在创建AnnotationConfigApplicationContext时候,把该类也加上;
* 3. 在主配置类中中加上
* */
public class JDBCConfig {
@Value("${driverClass}")
private String driverClass;
@Value("${jdbcURL}")
private String jdbcURL;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
@Bean
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl(jdbcURL);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
}
}
主配置类
package zte.com.business.config;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
/** a. @Configuration
* 1. 表明这个是一个配置类,作用和bean.xml一样
* 2. AnnotationConfigApplicationContext对象创建时添上该类时候,可以不写该注解
*
* b. @ComponentScan
* 1. value属性和basepackage属性一样,值为数组,如果只有一个,则可以省略{}
*
* c.@Import
* 1. 加载其他的副配置类
*
* d. @Bean
* 1. 将方法的返回值存入到容器中,默认key为方法名;
* 2. value和name属性作用一样;
* 3. 如果方法有参数,spring会去容器中查找,功能和Autowired一样的
*
* e. @PropertySource
* 1. 配置文件的路径,value属性指定路径;
* 2. 要加上classpath;
*/
@Configuration
@ComponentScan(basePackages = {"zte.com.business"})
@Import(JDBCConfig.class)
@PropertySource(value = "classpath:jdbc.properties")
public class IOCConfig {
@Bean(value = "getQueryRunner")
@Scope(value = "prototype")
public QueryRunner getQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
}
测试类
- 测试类中,service层的具体实现依然要用容器去手动去取,但dao层的具体实现就可以用自动注入的方式;
- 因为junit测试并不知道当前测试是基于Spring的IOC,因此不可能注入service层的对象;
- 因此引入下面的junit与spring的整合,从而就不用手动去容器中取对象;
package com.test;
public class StudentTest {
public static ApplicationContext ac;
public static IStudentService studentServiceImpl;
@Before
public void init(){
// 需要更换具体的容器类,为Config的字节码文件
ac = new AnnotationConfigApplicationContext(IOCConfig.class);
studentServiceImpl = (IStudentService) ac.getBean("studentServiceImpl");
}
@Test
public void findAll() {
List<Student> list = studentServiceImpl.findAllStudent();
System.out.println(list);
}
@Test
public void findById() {
Student student = studentServiceImpl.findById(2);
System.out.println(student);
}
@Test
public void deleteByid() {
studentServiceImpl.deleteById(5);
}
@Test
public void insertOne() {
Student student = new Student();
student.setId(5);
student.setName("zhang");
studentServiceImpl.saveStudent(student);
}
}
三、junit整合spring
pom.xml依赖(spring整合junit)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring_ioc_xml</groupId>
<artifactId>zte</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--Dbutils依赖-->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<!--c3p0依赖-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--spring整合junit, 5.2.6要求 junit是4.12及以上版本-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
</dependencies>
</project>
测试类
package com.test;
/** 1. 添加spring整合junit的pom依赖;
* 2. 使用junit的一个注解,将junit的main方法替换成spring提供的main方法;
* 3. 告知spring的运行器,sping的IOC容器是基于xml的还是基于注解的,并说明位置,
* spring提供的main方法,会去加载自动创建容器,不用手动创建;
* @ContextConfiguration
* locations : 指定xml的位置,加上classpath关键字
* */
//@ContextConfiguration(locations = "classpath:bean.xml")
@ContextConfiguration(classes = IOCConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentTest {
@Autowired
public IStudentService studentServiceImpl;
@Test
public void findAll() {
List<Student> list = studentServiceImpl.findAllStudent();
System.out.println(list);
}
@Test
public void findById() {
Student student = studentServiceImpl.findById(2);
System.out.println(student);
}
@Test
public void deleteByid() {
studentServiceImpl.deleteById(5);
}
@Test
public void insertOne() {
Student student = new Student();
student.setId(5);
student.setName("zhang");
studentServiceImpl.saveStudent(student);
}
}