JdbcTemplate
「JdbcTemplate概述」
它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。使用JdbcTemplate方便实现对数据库操作。
spring框架为我们提供了很多的操作模板类,如下所示:
| ORM持久化技术 | 模板类 |
|---|---|
| JDBC | org.springframework.jdbc.core.JdbcTemplate |
| Hibernate | org.springframework.orm.hibernate5.HibernateTemplate |
| IBatis(MyBatis) | org.springframework.orm.ibatis.SqlMapClientTemplate |
| JPA | org.springframework.orm.jpa.JpaTemplate |
来看下JdbcTemplate类:
「Spring中配置数据源」
1)配置C3P0数据源
<!--配置C3P0数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis_demo" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
2)配置DBCP数据源
<!--配置DBCP数据源-->
<bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
3)配置spring内置数据源
<!--配置spring内置数据源-->
<bean id="dataSource3" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
4)配置文件配置数据源
在src路径下定义jdbc.properties配置文件
引入外部的属性文件:
<!--引入外部属性文件:第一种方式【废弃⚠️】-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<!--引入外部属性文件:第二种方式-->
<context:property-placeholder location="classpath:jdbc.properties" />
「JdbcTemplate增删改查」
前置准备
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
spring配置JdbcTemplate
<!--配置一个数据库的操作模板:JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
1)基本操作-execute
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
jdbcTemplate.execute("insert into account(name, money) values ('test1', 5000.0)");
}
2)保存操作-update
@Test
public void testInsert() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
jdbcTemplate.update("insert into account(name, money) values (?,?)", "update-insert", 100);
}
3)更新操作-update
@Test
public void testUpdate() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
jdbcTemplate.update("update account set money = money-? where id = ?", 30, 2);
}
4)删除操作-update
@Test
public void testDelete() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
jdbcTemplate.update("delete from account where id = ?", 1);
}
5)查询多条-query
public class AccountRowMapper implements RowMapper<Account> {
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}
@Test
public void testQueryAll() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
List<Account> accounts = jdbcTemplate.query("select * from account where money >= ?", new AccountRowMapper(), 100);
for (Account account : accounts) {
System.out.println(account);
}
}
6)查询一条-query
使用RowMapper的方式(常用的方式)
@Test
public void testQueryOne() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new AccountRowMapper(), 3);
System.out.println(accounts.isEmpty() ? "没有查询结果" : accounts.get(0));
}
使用ResultSetExtractor的方式(不常用的方式)
@Test
public void testQueryOne2() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
Account account = jdbcTemplate.query("select * from account where id = ?", new AccountResultSetExtractor(), 3);
System.out.println(account);
}
7)查询返回一行一列
@Test
public void testQueryForObject() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
Integer total = jdbcTemplate.queryForObject("select count(*) from account where money > ?", Integer.class, 100);
System.out.println(total);
}
「dao中使用JdbcTemplate」
准备实体类(略)和Dao层接口
public interface AccountDao {
// 根据id查询账户信息
Account findAccountById(Integer id);
// 根据名称查询账户信息
Account findAccountByName(String name);
// 更新账户信息
void updateAccount(Account account);
}
1)dao中定义JdbcTemplate
方式1:在dao中定义JdbcTemplate。需要给dao注入JdbcTemplate
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
// 给dao注入JdbcTemplate
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer id) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new AccountRowMapper(), id);
return accounts.isEmpty() ? null : accounts.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new AccountRowMapper(), name);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果不唯一,不只有一个该名称的账户对象");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ?", account.getMoney(), account.getId());
}
}
配置文件:
<?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="accountDao" class="com.code.dao.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!--配置一个数据库的操作模板:JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo" />
<property name="username" value="root" />
<property name="password" value="root1234" />
</bean>
</beans>
测试代码:
public class CLient {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
AccountDao accountDao = (AccountDao) context.getBean("accountDao");
System.out.println(accountDao.findAccountById(5));
// System.out.println(accountDao.findAccountByName("test"));
System.out.println(accountDao.findAccountByName("demo"));
System.out.println(accountDao.findAccountByName("spring"));
Account account = new Account();
account.setId(2);
account.setMoney(29.9f);
accountDao.updateAccount(account);
}
}
这种方式1下面其实是有问题的:我们的dao有很多时,每个dao都有一些重复性的代码:
private JdbcTemplate jdbcTemplate;
// 给dao注入JdbcTemplate
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
我们使用下面的方式给他抽取出来
2)dao继承JdbcDaoSupport
JdbcDaoSupport 是spring框架为我们提供的一个类,该类中定义了一个JdbcTemplate对象,我们可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源,具体源码如下:
public abstract class JdbcDaoSupport extends DaoSupport {
//定义对象
private JdbcTemplate jdbcTemplate;
//set方法注入数据源,判断是否注入了,注入了就创建JdbcTemplate
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) { //如果提供了数据源就创建JdbcTemplate
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
//使用数据源创建JdcbTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
//当然,我们也可以通过注入JdbcTemplate对象
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
//使用getJdbcTmeplate方法获取操作模板对象
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
此版本dao,只需要 给它的父类注入一个数据源:
// 此版本dao,只需要给它的父类注入一个数据源
public class AccountDaoImpl2 extends JdbcDaoSupport implements AccountDao {
@Override
public Account findAccountById(Integer id) {
// getJdbcTemplate()方法是从父类上继承下来的
List<Account> accounts = getJdbcTemplate().query("select * from account where id = ?", new AccountRowMapper(), id);
return accounts.isEmpty() ? null : accounts.get(0);
}
@Override
public Account findAccountByName(String name) {
// getJdbcTemplate()方法是从父类上继承下来的
List<Account> accounts = getJdbcTemplate().query("select * from account where name = ?", new AccountRowMapper(), name);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果不唯一,不只有一个该名称的账户对象");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
// getJdbcTemplate()方法是从父类上继承下来的
getJdbcTemplate().update("update account set money = ? where id = ?", account.getMoney(), account.getId());
}
}
配置文件如下:
<bean id="accountDao2" class="com.code.dao.AccountDaoImpl2">
<property name="dataSource" ref="dataSource" />
</bean>
测试代码同上,不再赘述
那么两版Dao有什么区别呢?
第一种在Dao类中定义JdbcTemplate的方式,适用于所有配置方式(xml和注解都可以)。
第二种让Dao继承JdbcDaoSupport的方式,只能用于基于XML的方式,注解用不了。
事务控制
事务是数据库操作最基本单元,逻辑上的一组操作,要么都成功,如果有一个失败所有操作都失败。
事务的四个特性(ACID):
- 原子性(不可再分割,要么成功,要么都失败)
- 一致性(操作之前和之后总量不变)
- 隔离性(多事务之间不会产生影响)
- 持久性(事务提交后表中数据真正会变化)
「事务案例」
@Repository(value = "userDao")
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
// 少钱-lucy减少100
@Override
public void reduceMoney() {
String sql = "update account set money=money-? where name=?";
jdbcTemplate.update(sql, 100, "lucy");
}
// 多钱-mary增加100
@Override
public void addMoney() {
String sql = "update account set money=money+? where name=?";
jdbcTemplate.update(sql, 100, "mary");
}
}
@Service(value = "userService")
public class UserService {
@Resource(name = "userDao")
private UserDao userDao;
// 转账方法
public void accountMoney(){
userDao.reduceMoney();
userDao.addMoney();
}
}
上面代码,如果正常执行没有问题的。但是如果代码执行过程中出现异常,就会有问题。如:
// 转账方法
public void accountMoney(){
userDao.reduceMoney();
int i=10/0; // 模拟异常
userDao.addMoney();
}
执行结果就会导致:
解决思路:
// 转账方法
public void accountMoney(){
try {
// 第一步,开启事务
// 第二步,进行业务操作
userDao.reduceMoney();
// 模拟异常
int i=10/0;
userDao.addMoney();
// 第三步,没有发生异常的话,提交事务
} catch (Exception e){
// 第四步,出现异常,事务回滚
}
}
「Spring事务控制」
JavaEE体系进行分层开发,事务处理位于业务逻辑层(Service层),Spring提供了分层设计业务层的事务处理解决方案。spring的事务控制都是基于AOP的
spring框架为我们提供了一组事务控制的接口。这组接口是在spring-tx-4.2.4.RELEASE.jar中。(默认工程有此jar包)
「事务控制API」
1)PlatformTransactionManager
此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法:
- 获取事务状态信息
- TransactionStatus getTransaction(@Nullable TransactionDefinition var1)
- 提交事务
- void commit(TransactionStatus var1)
- 回滚事务
- void rollback(TransactionStatus var1)
开发中都是使用它的实现类:(真正管理事务的对象)
其中:
DataSourceTransactionManager:使用Spring JDBC或iBatis进行持久化数据时使用- HibernateTransactionManager:使用Hibernate版本进行持久化数据时使用
2)TransactionDefinition
它是事务的定义信息对象,里面有如下方法:
- 获取事务对象名称
- String getName()
- 获取事务隔离级别
- int getIsolationLevel()
- 获取事务传播行为
- int getPropagationBehavior()
- 获取事务超时时间
- int getTimeout()
- 获取事务是否只读
- boolean isReadOnly()
3)TransactionStatus
此接口提供的是事务具体的运行状态
- 获取是否存在存储点
- boolean hasSavepoint();
- 刷新事务
- void flush();
- 获取事务是否为新的事务
- boolean isNewTransaction();
- 设置事务回滚
- void setRollbackOnly();
- 获取事务是否回滚
- boolean isRollbackOnly();
- 获取事务是否完成
- boolean isCompleted();
「注解方式事务管理」
第一步:在spring配置文件配置事务管理器
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
第二步:在spring配置文件,开启事务注解
<beans
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager">
</tx:annotation-driven>
第三步:在service类上面(或者service类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也可以添加方法上面
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,为这个方法添加事务
// 转账方法
@Transactional
public void accountMoney() {
userDao.reduceMoney();
// 模拟异常
int i = 10 / 0;
userDao.addMoney();
}
「事务参数」
注解@Transactional,在这个注解里面可以配置事务相关参数:
(1)ioslation:事务的隔离级别(反映事务提交并发访问时的处理态度)
不考虑隔离型,会有三个读问题:脏读、不可重复读、虚(幻)读
脏读:A事务和B事务操作一份数据,B修改了数据,A读到了B修改之后的,最后B回滚了事务。回滚之后数据就错误了。
不可重复读(一个未提交事务读取到另一已提交事务修改后的数据):A事务和B事务读取到了一份数据,B修改后提交了事务,表中数据已变更,但是A这时候就能读取到B提交之后的数据。
虚读:一个未提交事务读取到另一提交事务添加数据(和不可重复读的区别是,这里读取到的是B事务添加的数据)
- int ISOLATION_DEFAULT = -1; // 默认级别,归属下列某一种
- int ISOLATION_READ_UNCOMMITTED = 1; // 可以读取未提交数据
- int ISOLATION_READ_COMMITTED = 2; // 只能读取已提交数据,解决脏读问题(Oracle默认级别)
- int ISOLATION_REPEATABLE_READ = 4; // 是否读取其他事务提交修改后的数据,解决不可重复读问题(Mysql默认级别)
- int ISOLATION_SERIALIZABLE = 8; // 是否读取其他事务提交添加后的数据,解决幻影读问题
// 转账方法
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
public void accountMoney() {}
(2)propagation:事务的传播行为(多事务方法直接进行调用,这个过程中事务是如何进行管理的)
Spring中定义的7种类传播行为:
- REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
- 例如:add()方法里调用update()方法。如果add里面有事务,则update也会使用add里面的事务;如果add里面没有事务,调用update则会创建新事务
- SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
- MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
- REQUERD_NEW:新建事务,如果当前在事务中,把当前事务挂起。
- 例如:add()方法里调用update(),无论add是否有事务,都会创建新的事务
- NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
- NEVER:以非事务方式运行,如果当前存在事务,抛出异常
- NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。
// 转账方法
@Transactional(propagation = Propagation.REQUIRED)
public void accountMoney() {}
(3)timeout:超时时间
事务需要在一定时间内进行提交,如果不提交进行回滚
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
(4)readOnly:是否是只读业务:
readOnly默认值false,表示可以查询,可以添加修改删除操作
设置readOnly值是true之后,只能查询
(5)rollbackFor:回滚
设置出现哪些异常进行事务回滚
(6)noRollbackFor:不回滚
设置出现哪些异常不进行事务回滚
「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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.transaction" />
<!--配置一个数据库的操作模板:JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo" />
<property name="username" value="root" />
<property name="password" value="root1234" />
</bean>
<!--1、创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2、配置通知-->
<tx:advice id="txadvice">
<!--配置事务参数-->
<tx:attributes>
<!--指定哪种规则的方法上面添加事务-->
<tx:method name="accountMoney" propagation="REQUIRED"/>
<!--<tx:method name="account*"/>-->
</tx:attributes>
</tx:advice>
<!--3、配置切入点和切面-->
<aop:config>
<aop:pointcut id="pt" expression="execution(* com.transaction.UserService.*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"></aop:advisor>
</aop:config>
</beans>
「完全注解方式事务管理」
创建配置类,使用配置类替代xml配置文件
注意:需要在service类上面(或者service类里面方法上面)添加事务注解@Transactional
@Configuration // 表示一个配置类
@ComponentScan(basePackages = "com.transaction") // 组件扫描
@EnableTransactionManagement // 开启事务
public class TxConfig {
// 创建数据库连接池
@Bean
public DriverManagerDataSource getDriverManagerDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis_demo");
dataSource.setUsername("root");
dataSource.setPassword("root1234");
return dataSource;
}
// 创建JdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
// 创建事务管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
Spring5新功能
「整合log4j2日志」
第一步:引入jar包
第二步:创建log4j2.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,
当设置成trace时,可以看到log4j2内部各种详细输出-->
<configuration status="INFO">
<!--先定义所有的appender-->
<appenders>
<!--输出日志信息到控制台-->
<console name="Console" target="SYSTEM_OUT">
<!--控制日志输出的格式-->
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</console>
</appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
<!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出-->
<loggers>
<root level="info">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
「@Nullable注解」
@Nullable 注解可以使用在方法上面、属性上面、参数上面,表示方法返回可以为空,属性值可以为空,参数值可以为空
注解用在方法上面,方法返回值可以为空:
@Nullable
String getId();
@Nullable
ApplicationContext getParent();
注解使用在方法参数里面,方法参数可以为空:
public <T> void registerBean(@Nullable String beanName, Class<T> beanClass, @Nullable Supplier<T> supplier, BeanDefinitionCustomizer... customizers) {
this.reader.registerBean(beanClass, beanName, supplier, customizers);
}
注解使用在属性上面,属性值可以为空:
@Nullable
private String bookName;
「函数式风GenericApplicationContext」
函数式风格创建对象,交给spring进行管理
@Test
public void testGenericApplicationContext() {
// 1、创建 GenericApplicationContext 对象
GenericApplicationContext context = new GenericApplicationContext();
// 2、调用 context 的方法进行对象注册
context.refresh();
context.registerBean("user", User.class, () -> new User());
// 3、获取在 spring 注册的对象
User user = (User) context.getBean("user");
System.out.println(user); // com.lamb.User@68bbe345
}
「整合Junit5」
jar包:
整合 JUnit4:
@RunWith(SpringJUnit4ClassRunner.class) //单元测试框架
@ContextConfiguration("classpath:tx.xml") //加载配置文件
public class JTest4 {
@Autowired
private UserService userService;
@Test
public void test1(){
userService.accountMoney();
}
}
整合 JUnit5:
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class JTest5 {
@Autowired
private UserService userService; @Test
public void test1() {
userService.accountMoney();
}
}
使用一个复合注解替代上面两个注解完成整合:
@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class JTest5 {
@Autowired
private UserService userService;
@Test
public void test1() {
userService.accountMoney();
}
}
「Webflux」
1)Webflux基本概念
是Spring5添加的新模块,用于web开发的,功能和SpringMVC类似的。使用响应式编程出现的框架。
使用传统web框架,比如SpringMVC,这些基于Servlet容器。而Webflux是一种异步非阻塞的框架,异步非阻塞的框架在Servlet3.1以后才支持,核心是基于Reactor的相关API实现的。
异步非阻塞:
- 异步和同步针对调用者。调用者发送请求,如果等着对方回应之后才去做其他事情就是同步,如果发送请求之后不等着对方回应就去做其他事情就是异步
- 阻塞和非阻塞针对被调用者。被调用者受到请求之后,做完请求任务之后才给出反馈就是阻塞,受到请求之后马上给出反馈然后再去做事情就是非阻塞
Webflux特点:
- 非阻塞式:在有限资源下,提高系统吞吐量和伸缩性,以Reactor为基础实现响应式编程
- 函数式编程:Spring5框架基于java8,Webflux使用函数式编程方式实现路由请求
Webflux和SpringMVC相比:
- 两个框架都可以使用注解方式,都运行在Tomet等容器中
- SpringMVC采用命令式编程,Webflux采用异步响应式编程
2)响应式编程(Java 实现)
什么是响应式编程:
响应式编程是一种面向数据流和变化传播的编程范式。这意味着可以在编程语言中很方便地表达静态或动态的数据流,而相关的计算模型会自动将变化的值通过数据流进行传播。
电子表格程序就是响应式编程的一个例子。单元格可以包含字面值或类似"=B1+C1"的公式,而包含公式的单元格的值会依据其他单元格的值的变化而变化。
Java8及其之前版本,提供的 观察者模式(观察关心的数据的变化) 的两个类: Observer 和 Observable
public class ObserverDemo extends Observable {
public static void main(String[] args) {
ObserverDemo observer = new ObserverDemo();
// 添加观察者
observer.addObserver((o, arg)->{
System.out.println("发生变化" + o);
});
observer.addObserver((o, arg)->{
System.out.println("收到被观察者通知,准备改变" + o);
});
observer.setChanged(); // 让数据变化
observer.notifyObservers(); // 通知,之后才能知道数据的变化
}
}
3)响应式编程(Reactor 实现)
响应式编程操作中,Reactor是满足Reactive规范的框架
Reactor有两个核心类,Mono和Flux,这两个类实现Publisher接口,提供丰富操作符。Flux对象实现发布者,返回N个元素;Mono实现发布者,返回0或者1个元素。
Flux和Mono都是数据流的发布者,使用Flux和Mono都可以发出三种数据信号: 元素值、错误信号、完成信号。错误信号和完成信号都代表终止信号,终止信号用于告诉订阅者数据流结束了,错误信号终止数据流同时把错误信息传递给订阅者。
第一步,引入依赖:
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.1.5.RELEASE</version>
</dependency>
第二步,代码演示Mono和Flux:
public class ReactorDemo {
public static void main(String[] args) {
// just方法直接声明
Flux.just(1, 2, 3, 4);
Mono.just(1);
// 其他的方法
Integer[] array = {1, 2, 3, 4};
Flux.fromArray(array);
List<Integer> list = Arrays.asList(array);
Flux.fromIterable(list);
Stream<Integer> stream = list.stream();
Flux.fromStream(stream);
}
}
三种信号特点:
- 错误信号和完成信号都是终止信号,不能共存的
- 如果没有发送任何元素值,而是直接发送错误或者完成信号,表示是空数据流
- 如果没有错误信号,没有完成信号,表示是无限数据流
调用just或者其他方法只是声明数据流,数据流并没有发出。只有进行订阅(subscribe()方法)之后才会触发数据流,不订阅什么都不会发生的!
Flux.just(1, 2, 3, 4).subscribe(System.out::print);
Mono.just(1).subscribe(System.out::print);
操作符:对数据流进行一道道操作,成为操作符,比如工厂流水线
[1] map:元素映射为新元素
[2] flatMap:元素映射为流
把每个元素转换流,把转换之后多个流合并大的流
4)执行流程和核心API
SpringWebflux基于Reactor,默认使用容器是Netty,Netty是高性能的NIO框架、异步非阻塞的框架
BIO:
NIO:
SpringWebflux执行过程和SpringMVC相似
SpringWebflux核心控制器 DispatchHandler,实现接口 WebHandler。接口WebHandler有一个方法:
SpringWebflux里面DispatcherHandler,负责请求的处理:
- HandlerMapping:请求查询到处理的方法
- HandlerAdapter:真正负责请求处理
- HandlerResultHandler:响应结果处理
SpringWebflux实现函数式编程,两个接口:RouterFunction(路由处理) 和 HandlerFunction(处理函数)
5)基于注解编程模型
SpringWebflux实现方式有两种:注解编程模型和函数式编程模型
使用注解编程模型方式,和之前SpringMVC使用相似的,只需要把相关依赖配置到项目中, SpringBoot自动配置相关运行容器,默认情况下使用Netty服务器。
第一步:创建SpringBoot工程,引入Webflux依赖
第二步:配置启动的端口号
第三步:创建包和相关类
实体类:
public class User {
private String name;
private String gender;
private Integer age;
public User(String name, String gender, Integer age) {
this.name = name;
this.gender = gender;
this.age = age;
}
...
}
创建接口定义操作的方法:
// 用户操作接口
public interface UserService {
// 根据id查询用户(返回0~1个元素)
Mono<User> getUserById(int id);
// 查询所有用户(返回多个元素)
Flux<User> getAllUser();
// 添加用户
Mono<Void> saveUserInfo(Mono<User> user);
}
接口实现类:
@Service
public class UserServiceImpl implements UserService{
// 造一批数据测试用
private final Map<Integer, User> users = new HashMap<>();
public UserServiceImpl() {
this.users.put(1, new User("user1", "male", 18));
this.users.put(2, new User("user2", "female", 19));
this.users.put(3, new User("user3", "female", 20));
}
// 根据id查询用户(返回0~1个元素)
@Override
public Mono<User> getUserById(int id) {
return Mono.justOrEmpty(this.users.get(id));
}
// 查询所有用户(返回多个元素)
@Override
public Flux<User> getAllUser() {
return Flux.fromIterable(this.users.values());
}
// 添加用户
@Override
public Mono<Void> saveUserInfo(Mono<User> user) {
return user.doOnNext(person -> {
// 向map集合里面放值
users.put(users.size() + 1, person);
}).thenEmpty(Mono.empty()); // 操作之后把Mono中的值清空
}
}
创建controller:
@RestController
public class UserController {
// 注入service
@Autowired
private UserService userService;
// 根据id查询用户(返回0~1个元素)
@GetMapping("/user/{id}")
public Mono<User> getUserById(@PathVariable int id){
return userService.getUserById(id);
}
// 查询所有用户(返回多个元素)
@GetMapping("/user")
public Flux<User> getAllUser(){
return userService.getAllUser();
}
// 添加用户
@PostMapping("/user/save")
public Mono<Void> saveUserInfo(@RequestBody User user){
Mono<User> userMono = Mono.just(user);
return userService.saveUserInfo(userMono);
}
}
启动程序:
测试结果:
SpringMVC方式实现,同步阻塞的方式,基于SpringMVC+Servlet+Tomcat
SpringWebflux方式实现,异步非阻塞方式,基于SpringWebflux+Reactor+Netty
6)基于函数式编程模型
在使用函数式编程模型操作时候,需要自己初始化服务器
基于函数式编程模型时候,有两个核心接口:RouterFunction(实现路由功能,请求转发给对应的handler) 和 HandlerFunction(处理请求生成响应的函数)。核心任务定义两个函数式接口的实现并且启动需要的服务器。
SpringWebflux请求和响应不再是ServletRequest和ServletResponse,而是 ServerRequest 和 ServerResponse
第一步:把注解编程模型工程复制一份 ,保留entity和service内容
第二步:创建Handler(具体实现方法)
public class UserHandler {
private final UserService userService;
public UserHandler(UserService userService) {
this.userService = userService;
}
// 根据id查询用户(返回0~1个元素)
public Mono<ServerResponse> getUserById(ServerRequest request) {
// 获取id值
int userId = Integer.valueOf(request.pathVariable("id"));
// 空值处理
Mono<ServerResponse> notFound = ServerResponse.notFound().build();
// 调用service方法得到数据
Mono<User> userMono = this.userService.getUserById(userId);
// 把userMono进行转换,再返回。使用Reactor操作符flatMap
return userMono.flatMap(person -> ServerResponse.ok().
contentType(MediaType.APPLICATION_JSON).
body(fromObject(person)).switchIfEmpty(notFound));
}
// 查询所有用户(返回多个元素)
public Mono<ServerResponse> getAllUser(ServerRequest request) {
// 调用service得到结果
Flux<User> users = this.userService.getAllUser();
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).
body(users, User.class);
}
// 添加用户
public Mono<ServerResponse> saveUser(ServerRequest request) {
// 得到user对象
Mono<User> userMono = request.bodyToMono(User.class);
return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
}
}
第三步:初始化服务器,编写Router
创建路由的方法:
public class Server {
/**
* 创建路由的方法:创建Router路由
*/
public RouterFunction<ServerResponse> routingFunction() {
// 创建hanler对象
UserService userService = new UserServiceImpl();
UserHandler handler = new UserHandler(userService);
// 设置路由
return RouterFunctions.route(
GET("/users/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::getUserById).
andRoute(GET("/users").and(accept(MediaType.APPLICATION_JSON)), handler::getAllUser);
}
}
创建服务器完成适配:
/**
* 创建服务器完成适配
*/
public void createReactorServer(){
// 路由和handler适配
RouterFunction<ServerResponse> route = routingFunction();
HttpHandler httpHandler = toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
// 创建服务器
HttpServer httpServer = HttpServer.create();
httpServer.handle(adapter).bindNow();
}
调用测试:
第四步:使用WebClient调用
/**
* 使用 WebClient 调用
*/
public class Client {
public static void main(String[] args) {
// 调用服务器地址
WebClient webClient = WebClient.create("http://127.0.0.1:53311");
// 根据id查询
User user = webClient.get().uri("/users/{id}", "1")
.accept(MediaType.APPLICATION_JSON).retrieve().bodyToMono(User.class).block();
System.out.println("###############" + user.getName()); // ###############user1
// 查询所有
Flux<User> userFlux = webClient.get().uri("/users")
.accept(MediaType.APPLICATION_JSON).retrieve().bodyToFlux(User.class);
userFlux.map(use -> use.getName()).buffer().doOnNext(System.out::println).blockFirst();
// [user1, user2, user3]
}
}
σ(^_^)