目录
一、Spring配置数据源
1.1 数据源(连接池)的作用
1.2数据源的使用
1.3基本实现
1.4.抽取配置文件,降低耦合性(druid)
1.4.1抽取jdbc.properties文件
1.4.2设置数据源的基本连接数据,通过applicationContext.xml设置数据库参数applicationContext.xml
1.4.3抽取jdbc配置文件
二、Spring注解开发
2.1 原注解(时间的先后区分的)
2.1.1测试数据准备
2.1.2 替换dao层
2.1.3替换Service层
2.1.4 提高可读性(注解的功能是一样的,不过更加具有可读性),如果使用注解,Service层可以不写setUserdao方法,如果使用注解,则必须写
2.1.5 普通值进行注入@Value()
2.2 新注解:使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
2.2.1 测试资料
2.2.2 替换组件扫描
2.2.3, 替换 bean id="dataSource
三、Spring集成Junit
一、Spring配置数据源
1.1 数据源(连接池)的作用
• 数据源(连接池)是提高程序性能如出现的
• 事先实例化数据源,初始化部分连接资源
• 使用连接资源时从数据源中获取
• 使用完毕后将连接资源归还给数据源
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等
1.2数据源的使用
1 导入数据源的坐标和数据库驱动坐标
2 创建数据源对象
3 设置数据源的基本连接数据
4 使用数据源获取连接资源和归还连接资源
1.3基本实现
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.15</version> </dependency> <dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/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.11</version><scope>test</scope>
public class DataSourceTest {@Testpublic void test() throws Exception {ComboPooledDataSource dataSource= new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day17");dataSource.setUser("root");dataSource.setPassword("12345678");//获得连接对象Connection connection = dataSource.getConnection();System.out.println(connection);}@Testpublic void test2() throws Exception {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");dataSource.setUrl("jdbc:mysql://localhost:3306/day17");dataSource.setUsername("root");dataSource.setPassword("12345678");Connection connection = dataSource.getConnection();System.out.println(connection);}
}
1.4.抽取配置文件,降低耦合性(druid)
1.4.1抽取jdbc.properties文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///day17
username=root
password=12345678
initialSize=5
maxActive=10
maxWait=3000
直接读取properties文件
public class DataSourceTest {@Testpublic void testC3P0ByProperties() throws Exception { //加载类路径下的jdbc.properties//资源束包含区域特定的对象。 当您的程序需要特定于区域设置的资源时,例如String ,// 您的程序可以从适合当前用户的区域设置的资源包中加载它。 以这种方式,您可以编写程序代码,// 这个程序代码大部分独立于用户的区域设置,以隔离资源束中大部分(如果不是全部)特定于区域设置的信息。ResourceBundle rb = ResourceBundle.getBundle("jdbc");DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(rb.getString("driverClassName"));dataSource.setUrl(rb.getString("url"));dataSource.setUsername(rb.getString("username"));dataSource.setPassword(rb.getString("password"));dataSource.setInitialSize(Integer.parseInt(rb.getString("initialSize")));dataSource.setMaxActive(Integer.parseInt(rb.getString("maxActive")));dataSource.setMaxWait(Long.parseLong(rb.getString("maxWait")));Connection connection = dataSource.getConnection();System.out.println(connection);}
}
1.4.2设置数据源的基本连接数据,通过applicationContext.xml设置数据库参数
applicationContext.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="UserDao" class="com.study.dao.impl.userDaoImpl" ></bean><bean id="Service" class="com.study.Service.impl.userServiceImpl"><property name="userDao" ref="UserDao"></property></bean><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property><property name="url" value="jdbc:mysql:///day17"/><property name="username" value="root"/><property name="password" value="12345678"/><property name="initialSize" value="5"/><property name="maxActive" value="10"/><property name="maxWait" value="3000"/></bean></beans>
进行测试
@Testpublic void test2() throws SQLException {ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");DataSource dataSource = (DataSource) app.getBean("dataSource");Connection connection = dataSource.getConnection();System.out.println(connection);}
1.4.3抽取jdbc配置文件
applicationContext.xml加载jdbc.properties配置文件获得连接信息。
首先,需要引入context命名空间和约束路径:
命名空间:xmlns:context="http://www.springframework.org/schema/context"
约束路径:http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
applicationContext.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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载外部property文件--><context:property-placeholder location="classpath:jdbc.properties"/><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${driverClassName}"></property><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/><property name="initialSize" value="${initialSize}"/><property name="maxActive" value="${maxActive}"/><property name="maxWait" value="${maxWait}"/></bean></beans>
测试:
public class DataSourceTest {@Testpublic void testC3P0ByProperties() throws Exception { //加载类路径下的jdbc.properties//资源束包含区域特定的对象。 当您的程序需要特定于区域设置的资源时,例如String ,// 您的程序可以从适合当前用户的区域设置的资源包中加载它。 以这种方式,您可以编写程序代码,// 这个程序代码大部分独立于用户的区域设置,以隔离资源束中大部分(如果不是全部)特定于区域设置的信息。ResourceBundle rb = ResourceBundle.getBundle("jdbc");DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(rb.getString("driverClassName"));dataSource.setUrl(rb.getString("url"));dataSource.setUsername(rb.getString("username"));dataSource.setPassword(rb.getString("password"));dataSource.setInitialSize(Integer.parseInt(rb.getString("initialSize")));dataSource.setMaxActive(Integer.parseInt(rb.getString("maxActive")));dataSource.setMaxWait(Long.parseLong(rb.getString("maxWait")));Connection connection = dataSource.getConnection();System.out.println(connection);}@Testpublic void test2() throws SQLException {ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");DataSource dataSource = (DataSource) app.getBean("dataSource");Connection connection = dataSource.getConnection();System.out.println(connection);}
}
到此为止:
applicationContext.xml加载jdbc.properties配置文件获得连接信息。
测试环境读取applicationContext.xml文件,不再依赖流输入
resources:下文件共有两个
jdbc.properties
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql:///day17 username=root password=12345678 initialSize=5 maxActive=10 maxWait=3000
applicationContext.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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载外部property文件--><context:property-placeholder location="classpath:jdbc.properties"/><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${driverClassName}"></property><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/><property name="initialSize" value="${initialSize}"/><property name="maxActive" value="${maxActive}"/><property name="maxWait" value="${maxWait}"/></bean></beans>
测试工具类:
package com.study.test;import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;/*** @author Alina* @date 2022年03月17日 11:34 下午*/
public class DataSourceTest {@Testpublic void test2() throws SQLException {ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");DataSource dataSource = (DataSource) app.getBean("dataSource");Connection connection = dataSource.getConnection();System.out.println(connection);}
}
二、Spring注解开发
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置 文件可以简化配置,提高开发效率。
Spring原始注解主要是替代<Bean>的配置
2.1 原注解(时间的先后区分的)
2.1.1测试数据准备
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>Spring-mvn-test</artifactId><version>1.0-SNAPSHOT</version><name>Spring-mvn-test</name><packaging>war</packaging><properties><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.source>1.8</maven.compiler.source><junit.version>5.7.1</junit.version></properties><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.16</version><scope>compile</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>com.example</groupId><artifactId>Spring-mvn-test</artifactId><version>1.0-SNAPSHOT</version><scope>compile</scope></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-web --><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.3.14</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.16</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.15</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><!-- https://mvnrepository.com/artifact/com.mchange/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.11</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>compile</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>compile</scope></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>3.3.1</version></plugin> </plugins></build> </project>
applicationContext.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="userDao" class="com.study.dao.impl.userDaoImpl"></bean><bean id="userService" class="com.study.Service.impl.userServiceImpl"><property name="userDao" ref="userDao"> </property></bean></beans>
package com.study.dao.impl;import com.study.dao.userDao;/*** @author Alina* @date 2022年03月16日 10:03 下午*/
public class userDaoImpl implements userDao {@Overridepublic void save() {System.out.println(" 你好");}}
package com.study.Service.impl;import com.study.Service.userService;
import com.study.dao.userDao;/*** @author Alina* @date 2022年03月16日 10:06 下午*/
public class userServiceImpl implements userService {private userDao userDao;public void setUserDao(userDao userDao) {this.userDao = userDao;}@Overridepublic void inke() {userDao.save();}
}
package com.study.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.study.Service.userService;/*** @author Alina* @date 2022年03月18日 1:12 上午*/
public class UserController {public static void main(String[] args) {ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");userService bean = app.getBean(userService.class);bean.inke();}
}
2.1.2 替换dao层
Component:组件 @Component("") 引号内可以加id
import com.study.dao.userDao;
import org.springframework.stereotype.Component;/*** @author Alina* @date 2022年03月16日 10:03 下午*/
//<bean id="userDao" class="com.study.dao.impl.userDaoImpl"></bean>@Component("userDao")
public class userDaoImpl implements userDao {@Overridepublic void save() {System.out.println(" 你好");}
}
2.1.3替换Service层
@Autowired:自动注入 @Qualifier(""):引号内写入要注入的bean
读到此处,先看下面的代码,整个读完二这个标号后再读这个位置更容易理解
如果bean只有一个,此处注解可以只写@Autowired,不写注解@Qualifier("")
如果bean有多个,为了方便找到bean,就需要同时出现这两个注解
当然这两个注解可以用@Resource(name=" ")代替
相当于@Autowired+@Qualifier,按照名称进行注入
package com.study.Service.impl;import com.study.Service.userService;
import com.study.dao.userDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;/*** @author Alina* @date 2022年03月16日 10:06 下午*/
// <bean id="userService" class="com.study.Service.impl.userServiceImpl">@Component("userService")
public class userServiceImpl implements userService {// <property name="userDao" ref="userDao"> </property>@Autowired@Qualifier("userDao")private userDao userDao;public void setUserDao(userDao userDao) {this.userDao = userDao;}@Overridepublic void inke() {userDao.save();}
}
此时,虽然applicationContext.xml文件中不需要bean标签进行配置,但是需要配置组件扫描,原因:因为使用注解进行配置,但是spring不知道,所以要告诉他使用的注解
No qualifying bean of type 'com.study.Service.userService' available
添加这个
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置组件扫描--><context:component-scan base-package="com.study"/> </beans>
2.1.4 提高可读性(注解的功能是一样的,不过更加具有可读性),如果使用注解,Service层可以不写setUserdao方法,如果使用注解,则必须写
//<bean id="userDao" class="com.study.dao.impl.userDaoImpl"></bean>
// @Component("userDao")@Repository("userDao")
public class userDaoImpl implements userDao {@Overridepublic void save() {System.out.println(" 你好");}}
// <bean id="userService" class="com.study.Service.impl.userServiceImpl">
// @Component("userService")@Service("userService")
public class userServiceImpl implements userService {// <property name="userDao" ref="userDao"> </property>@Autowired@Qualifier("userDao")private userDao userDao;@Overridepublic void inke() {userDao.save();}
}
暂时没有写web端,先用测试类
public class UserController {public static void main(String[] args) {ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");userService bean = app.getBean(userService.class);bean.inke();}
}
此处回到前面读蓝色字体,然后看代码
@Service("userService")
public class userServiceImpl implements userService {@Resource(name="userDao")private userDao userDao;@Overridepublic void inke() {userDao.save();}
}
2.1.5 普通值进行注入@Value()
@Value("张三")private String Name;
2.2 新注解:使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
非自定义的Bean的配置:<bean>
加载properties文件的配置:<context:property-placeholder>
组件扫描的配置:<context:component-scan>
引入其他文件:<import>
2.2.1 测试资料
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置组件扫描--><context:component-scan base-package="com.study"/><!-- 读取外部properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${driverClassName}"></property><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/><property name="initialSize" value="${initialSize}"/><property name="maxActive" value="${maxActive}"/><property name="maxWait" value="${maxWait}"/></bean> </beans>
jdbc.properties
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql:///day17 username=root password=12345678 initialSize=5 maxActive=10 maxWait=3000
package com.study.config;import org.springframework.context.annotation.Configuration;/*** @author Alina* @date 2022年03月18日 2:35 上午*/
//标志这是Spring的核心配置文件
@Configuration
public class SpringConfigration {
}
2.2.2 替换组件扫描
//标志这是Spring的核心配置文件
@Configuration
//标志这是Spring的核心配置文件
@Configuration@ComponentScan("com.study")
public class SpringConfigration {
}
2.2.3, 替换 bean id="dataSource
@Bean // Spring 会将当前方法的返回值以指定名称存储到Spring容器中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置组件扫描--><context:component-scan base-package="com.study"/><!-- 读取外部properties文件--><context:property-placeholder location="classpath:jdbc.properties"/></beans>
package com.study.config;import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;/*** @author Alina* @date 2022年03月18日 2:35 上午*/
//标志这是Spring的核心配置文件
@Configuration@ComponentScan("com.study")
public class SpringConfigration {@Test@Bean("dataSource") // Spring 会将当前方法的返回值以指定名称存储到Spring容器中public void getDataSource() throws SQLException {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");dataSource.setUrl("jdbc:mysql:///day17");dataSource.setUsername("root");dataSource.setPassword("12345678");dataSource.setInitialSize(5);dataSource.setMaxActive(19);dataSource.setMaxWait(3000);Connection connection = dataSource.getConnection();System.out.println(connection);}
}
2.2.4 替换 读取外部properties文件 理论上是这样,但是我的报错了,暂时不知道原因,稍后再Spingboot找到会更新 ,好像是版本问题
package com.study.config;import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
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 javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;/*** @author Alina* @date 2022年03月18日 2:35 上午*/
//标志这是Spring的核心配置文件
@Configuration
@ComponentScan("com.study")
//替换读取properties文件
@PropertySource("classpath:jdbc.properties")
public class SpringConfigration {@Value("${driverClassName}")private String driverClassName;@Value("${url}")private String url;@Value("${username}")private String username;@Value("${password}")private String password;@Value("${initialSize}")private int initialSize;@Value("${maxActive}")private int maxActive;@Value("${maxWait}")private int maxWait;@Test@Bean("dataSource") // Spring 会将当前方法的返回值以指定名称存储到Spring容器中public void getDataSource() throws SQLException {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driverClassName);System.out.println(driverClassName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);System.out.println(password);dataSource.setInitialSize(initialSize);System.out.println(initialSize);dataSource.setMaxActive(maxActive);dataSource.setMaxWait(maxWait);Connection connection = dataSource.getConnection();System.out.println(connection);}
}
三、Spring集成Junit
1 导入spring集成Junit的坐标
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
package com.study.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;@Configuration
@ComponentScan("com.study")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
package com.study.config;import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;import javax.sql.DataSource;
import java.beans.PropertyVetoException;/*** @author Alina* @date 2022年03月18日 4:18 上午*/
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Bean(name="dataSource")public DataSource getDataSource() throws PropertyVetoException {ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(driver);dataSource.setJdbcUrl(url);dataSource.setUser(username);dataSource.setPassword(password);return dataSource; }
}
2 使用@Runwith注解替换原来的运行期
3 使用@ContextConfiguration指定配置文件或配置类 4 使用@Autowired注入需要测试的对象
5 创建测试方法进行测试
package com.study.test;import com.study.Service.userService;
import com.study.config.SpringConfiguration;
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;/*** @author Alina* @date 2022年03月18日 3:57 上午*/@RunWith(SpringJUnit4ClassRunner.class)
//加载spring核心配置文件
//@ContextConfiguration(value = {"classpath:applicationContext.xml"}) //加载spring核心配置类
@ContextConfiguration(classes = {SpringConfiguration.class})public class springTest {@Autowiredprivate userService userService;@Testpublic void test(){userService.inke();}
}
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"></beans>