APP下载
报价宝  ›  科技  › 

Java架构:需要了解的Spring学习笔记

报价宝 来源:baojiabao.com 发布时间:2019-09-01 06:56:00 09月16日更新
报价宝综合消息Java架构:需要了解的Spring学习笔记

【Spring简介】

Spring 是一个开源框架,是一个分层的 JavaEE 一站式框架。

所谓一站式框架是指 Spring 有 JavaEE 开发的每一层解决方案。

1、WEB层:SpringMVC

2、Service层:Spring的Bean管理,宣告式事务

3、DAO层:Spring的JDBC模板,ORM模板

(一)、优点:

1、IOC:方便解耦合

2、AOP:对程式进行扩充套件

3、轻量级框架

4、方便与其他框架整合

【Spring使用】

(一)、Spring开发包解压后的目录介绍:

1、docs: Spring 开发规范和API

2、libs: Spring jar 包和源代码

3、schema: Spring 配置档案的约束

DataAccess 用于资料访问,WEB 用于页面显示,核心容器也就是IOC部分。

【控制反转(IOC)】

控制反转(Inversion of Control)是指将物件的建立权反转(交给)Spring。

使用IOC就需要汇入IOC相关的包,也就是上图中核心容器中的几个包:beans,context,core,expression四个包。

【实现原理】

传统方式建立物件:

UserDAO userDAO=new UserDAO();

进一步面向界面程式设计,可以多型:

UserDAO userDAO=new UserDAOImpl();

这种方式的缺点是界面和实现类高耦合,切换底层实现类时,需要修改源代码。程式设计应该满足OCP元祖,在尽量不修改程式源代码的基础上对程式进行扩充套件。此时,可以使用工厂模式:

class BeanFactory{

public static UserDAO getUserDAO(){

return new UserDAOImpl();

}

}

此种方式虽然在界面和实现类之间没有耦合,但是界面和工厂之间存在耦合。

使用工厂+反射+配置档案的方式,实现解耦,这也是 Spring 框架 IOC 的底层实现。

//xml配置档案

//

class BeanFactory{

public static Object getBean(String id){

//解析XML

//反射

Class clazz=Class.forName();

return clazz.newInstance();

}

}

【IOC XML 开发】

在 docs 档案中包含了 xsd-configuration.hmtl 档案。其中定义了 beans schema。

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

【呼叫类】:

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");

UserService userService=(UserService)applicationContext.getBean("userService");

userService.save();

【IOC 和 DI】

DI 指依赖注入,其前提是必须有 IOC 的环境,Spring 管理这个类的时候将类的依赖的属性注入进来。

例如,在UserServiceImpl.java中:

public class UserServiceImpl implements UserService{

private String name;

public void setName(String name){

this.name=name;

}

public void save(){

System.out.println("save "+name);

}

}

【在配置档案中】:

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">

【测试程式码】:

@Test

public void demo2(){

//建立Spring工厂

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");

UserService userService=(UserService)applicationContext.getBean("userService");

userService.save();

}

【执行结果】:

(一)save tony

可以看到,在配置档案中配置的属性,在 Spring 管理该类的时候将其依赖的属性成功进行了设定。如果不使用依赖注入,则无法使用界面,只能使用实现类来进行设定,因为界面中没有该属性。

【Spring 的工厂类】

(一)、BeanFactory: 老版本的工厂类,在呼叫getBean()方法时,才会生成类的例项。

(二)、ApplicationContext: 在载入配置档案的时候,就会将 Spring 管理的类都例项化。有两个实现类:

1、ClassPathXmlApplicationContext: 载入类路径下的配置档案

2、FileSystemXmlApplicationContext: 载入磁盘下的配置档案

【bean标签配置】

(一)、id: 唯一约束,不能出现特殊字元

(二)、name: 理论上可以重复,但是开发中最好不要。可以出现特殊字元

生命周期】:

1、init-method: bean被初始化的时候执行的方法

2、destroy-method: bean被销毁的时候执行的方法

【作用范围】:

scope: bean的作用范围,有如下几种,常用的是前两种

1、singleton: 预设使用单例模式建立

2、prototype: 多例

3、request: 在web专案中,spring 建立类后,将其存入到 request 范围中

4、session: 在web专案中,spring 建立类后,将其存入到 session 范围中

5、globalsession: 在web专案中,必须用在 porlet 环境

【属性注入设定】

(一)、构造方法方式的属性注入: Car 类在构造方法中有两个属性,分别为 name 和 price。

(二)、set 方法属性注入: Employee 类在有两个 set 方法,分别设定普通型别的 name 和引用型别的 Car (使用 ref 指向引用型别的 id 或 name)。

(三)、P名称空间的属性注入: 首先需要引入p名称空间:

//引入p名称空间

xmlns:p="http://www.springframework.org/schema/p"

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">

如果是普通属性

/

如果是引用型别:

SpEL(Spring Expression Language)属性注入(Spring 3.x以上版本)

集合型别属性注入:

qirui

baoma

benchi

【多模组开发配置】

1、在载入配置档案的时候,载入多个配置档案

2、在一个配置档案中引入多个配置档案,通过实现

【IOC 注解开发】

(一)、示例

1、引入jar包: 除了要引入上述的四个包之外,还需要引入aop包。

2、建立 applicationContext.xml ,使用注解开发引入 context 约束(xsd-configuration.html)

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.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

3、元件扫描: 使用IOC注解开发,需要配置元件扫描,也就是哪些包下的类使用IOC的注解。

4、在类上添加注解

5、使用注解设定属性的值

属性如果有set方法,将属性注入的注解新增到set方法

属性没有set方法,将注解新增到属性上。

@Component("UserDao")//相当于配置了一个 其id为UserDao,对应的类为该类

public class UserDAOImpl implements UserDAO {

@Override

public void save() {

// TODO Auto-generated method stub

System.out.println("save");

}

}

【注解详解】

(一)、@Component

元件注解,用于修饰一个类,将这个类交给 Spring 管理。

有三个衍生的注解,功能类似,也用来修饰类。

1、@Controller:修饰 web 层类

2、@Service:修饰 service 层类

3、@Repository:修饰 dao 层类

(二)、属性注入

1、普通属性使用 @Value 来设定属性的值

2、物件属性使用 @Autowired ,这个注解是按照型别来进行属性注入的。如果希望按照 bean 的名称或id进行属性注入,需要用 @Autowired 和 @Qualifier 一起使用

3、实际开发中,使用 @Resource(name=" ") 来进行按照物件的名称完成属性注入

(三)、其他注解

1、@PostConstruct 相当于 init-method,用于初始化函式的注解

2、@PreDestroy 相当于 destroy-method,用于销毁函式的注解

3、@Scope 作用范围的注解,常用的是预设单例,还有多例 @Scope("prototype")

【IOC 的 XML 和注解开发比较】

1、适用场景:XML 适用于任何场景;注解只适合自己写的类,不是自己提供的类无法添加注解。

2、可以使用 XML 管理 bean,使用注解来进行属性注入

【AOP开发】

AOP 是 Aspect Oriented Programming 的缩写,意为面向切面程式设计,通过预编译方式和执行期动态代理实现程式功能的统一维护的一种技术,是OOP的延续。

AOP 能够对程式进行增强,在不修改源代码的情况下,可以进行许可权校验,日志记录,效能监控,事务控制等。

也就是说功能分为两大类,一类是核心业务功能,一类是辅助增强功能。两类功能彼此独立进行开发。比如登入功能是核心业务功能,日志功能是辅助增强功能,如果有需要,将日志和登入编制在一起。辅助功能就称为切面,这种能选择性的、低耦合的把切面和核心业务功能结合的程式设计思想称为切面程式设计。

(一)、底层实现

JDK 动态代理只能对实现了界面的类产生代理。Cglib 动态代理可以对没有实现界面的类产生代理物件,生成的是子类物件。

使用 JDK 动态代理:

public interface UserDao {

public void insert();

public void delete();

public void update();

public void query();

}

实现类:

public class UserDaoImpl implements UserDao {

@Override

public void insert() {

System.out.println("insert");

}

@Override

public void delete() {

System.out.println("delete");

}

@Override

public void update() {

System.out.println("update");

}

@Override

public void query() {

System.out.println("query");

}

}

JDK 代理:

public class JDKProxy implements InvocationHandler{

private UserDao userDao;

public JDKProxy(UserDao userDao){

this.userDao=userDao;

}

public UserDao createProxy(){

UserDao userDaoProxy=(UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),

userDao.getClass().getInterfaces(), this);

return userDaoProxy;

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

if("update".equals(method.getName())){

System.out.println("许可权校验");

return method.invoke(userDao, args);

}

return method.invoke(userDao, args);

}

}

通过动态代理增强了 update 函式。 测试类:

public class Demo1 {

@Test

public void demo1(){

UserDao userDao=new UserDaoImpl();

UserDao proxy=new JDKProxy(userDao).createProxy();

proxy.insert();

proxy.delete();

proxy.update();

proxy.query();

}

}

执行结果为:

insert

delete

许可权校验

update

query

CglibCglib 是第三方开源代码生成类库,可以动态新增类的属性和方法。

与上边JDK代理不同,Cglib的使用方式如下:

public class CglibProxy implements MethodInterceptor{

//传入增强的物件

private UserDao customerDao;

public CglibProxy(UserDao userDao){

this.userDao=userDao;

}

public UserDao createProxy(){

Enhancer enhancer=new Enhancer();

enhancer.setSuperclass(userDao.getClass());

enhancer.setCallback(this);

UserDao proxy=(UserDao)enhancer.create();

return proxy;

}

@Override

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

if("save".equals(method.getName())){

System.out.println("enhance function");

return methodProxy.invokeSuper(proxy, args);

}

return methodProxy.invokeSuper(proxy, args);

}

}

如果实现了界面的类,底层采用JDK代理。如果不是实现了界面的类,底层采用 Cglib代理。

【IOC与传统方式的比较】

获取物件方式:传统通过 new 关键字主动建立一个物件。IOC 方式中,将物件的生命周期交给 Spring 管理,直接从 Spring 获取物件。也就是控制反转————将控制权从自己手中交到了 Spring 手中。

Spring 的 AOP 开发(AspectJ 的 XML 方式)

AspectJ 是一个 AOP 的框架,Spring 引入 AspectJ,基于 AspectJ 进行 AOP 的开发。

【相关术语】

1、Joinpoint: 连线点,可以被拦截到的点。也就是可以被增强的方法都是连线点。

2、Pointcut: 切入点,真正被拦截到的点,也就是真正被增强的方法

3、Advice: 通知,方法层面的增强。对某个方法进行增强的方法,比如对 save 方法进行许可权校验,许可权校验的方法称为通知。

4、Introduction: 引介,类层面的增强。

5、Target: 目标,被增强的物件(类)。

6、Weaving: 织入,将 advice 应用到 target 的过程。

7、Proxy: 代理物件,被增强的物件。

8、Aspect: 切面,多个通知和多个切入点的组合。

【使用方法】

(一)、引入相关包

(二)、引入配置档案

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

(三)、编写目标类并配置:

public class ProductDaoImpl implements ProductDao {

@Override

public void save() {

System.out.println("save");

}

@Override

public void update() {

System.out.println("update");

}

@Override

public void find() {

System.out.println("find");

}

@Override

public void delete() {

System.out.println("delete");

}

}

(四)、编写切面类,假设用于许可权验证并配置

public class MyAspectXML {

public void checkPri(){

System.out.println("check auth");

}

}

(五)、通过AOP配置完成对目标类的增强

【通知型别】

(一)、前置通知在目标方法执行前操作,可以获得切入点资讯

public void checkPri(JoinPoint joinPoint){

System.out.println("check auth "+joinPoint);

}

(二)、后置通知:在目标方法执行后操作,可以获得方法返回值

public void writeLog(Object result){

System.out.println("writeLog "+result);

}

(三)、环绕通知:在目标方法执行前和后操作,可以阻止目标方法执行

public Object around(ProceedingJoinPoint joinPoint) throws Throwable{

System.out.println("before");

Object result=joinPoint.proceed();

System.out.println("after");

return result;

}

(四)、异常丢掷通知:程式出现异常时操作

public void afterThrowing(Throwable ex){

System.out.println("exception "+ex.getMessage());

}

(五)、最终通知:相当于finally块,无论程式码是否有异常,都会执行

public void finallyFunc(){

System.out.println("finally");

}

(六)、引介通知:不常用

Spring 切入点表示式

基于 execution 函式完成

语法:[访问修饰符] 方法返回值 包名.类名.方法名(引数)

其中任意字段可以使用*代替表示任意值

【Spring 的 AOP 基于 AspectJ 注解开发】

(一)、开发步骤

1、引入jar包

2、设定配置档案:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

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/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd">

3、编写配置目标类

public class OrderDao {

public void save(){

System.out.println("save order");

}

public void update(){

System.out.println("update order");

}

public void delete(){

System.out.println("delete order");

}

public void find(){

System.out.println("find order");

}

}

4、开启aop注解自动代理

5、编写切面类并配置

@Aspect

public class MyAspectAnno {

@Before(value="execution(* demo1.OrderDao.save(..))")

public void before(){

System.out.println("before");

}

}

(二)、注解通知型别

1、@Before: 前置通知

2、@AfterReturning: 后置通知

@AfterReturning(value="execution(* demo1.OrderDao.save(..))",returning="result")

public void after(Object result){

System.out.println("after "+result);

}

3、@Around:环绕通知

@Around(value="execution(* demo1.OrderDao.save(..))")

public Object around(ProceedingJoinPoint joinPoint) throws Throwable{

System.out.println("before");

Object obj=joinPoint.proceed();

System.out.println("after");

return obj;

}

4、@AfterThrowing: 丢掷异常

@AfterThrowing(value="execution(* demo1.OrderDao.save(..))",throwing="e")

public void afterThrowing(Throwable e){

System.out.println("exception:"+e.getMessage();

}

5、@After: 最终通知

@After(value="execution(* demo1.OrderDao.save(..))")

public void after(){

System.out.println("finally");

}

6、@PointCut:切入点注解

@PointCut(value="execution(* demo1.OrderDao.save(..))")

private void pointcut1(){}

此时,在上述通知的注解中,value可以替换为该函式名,例如:

@After(value="MyAspect.pointcut1()")

public void after(){

System.out.println("finally");

}

这个注解的好处是,只需要维护切入点即可,不用在修改时修改每个注解。

【Spring 的 JDBC 模板】

Spring 对持久层也提供了解决方案,也就是 ORM 模组和 JDBC 的模板。针对 JDBC ,提供了 org.springframework.jdbc.core.JdbcTemplate 作为模板类。

(一)、使用 JDBC 模板

1、引入jar包,数据库驱动,Spring 的 jdbc 相关包。

2、基本使用:

public void demo1(){

//建立连线池

DriverManagerDataSource dataSource=new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql:///spring4");

dataSource.setUsername("root");

dataSource.setPassword("123456");

//建立JDBC模板

JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);

jdbcTemplate.update("insert into account values (null,?,?)", "xiaoming",1000d);

}

3、将连线池和模板交给 Spring 管理

配置档案:

测试档案:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration("classpath:applicationContext.xml")

public class JdbcDemo2 {

@Resource(name="jdbcTemplate")

private JdbcTemplate jdbcTemplate;

@Test

public void demo2(){

jdbcTemplate.update("insert into account values (null,?,?)", "xiaolan",1000d);

}

}

(二)、使用开源数据库连线池

1、使用 DBCP 的配置:

2、使用 C3P0 的配置:

3、引入外部属性档案

首先建立外部属性档案:

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://192.168.66.128/spring4

jdbc.username=root

jdbc.password=123456

然后对属性档案进行配置:

(三)、CRUD操作

insert, update, delete 语句都借助模板的 update 方法进行操作。

public void demo(){

jdbcTemplate.update("insert into account values (null,?,?)", "xiaoda",1000d);

jdbcTemplate.update("update account set name=?,money=? where id=?", "xiaoda",1000d,2);

jdbcTemplate.update("delete from account where id=?", 6);

}

查询操作:

public void demo3(){

String name=jdbcTemplate.queryForObject("select name from account where id=?",String.class,5);

long count=jdbcTemplate.queryForObject("select count(*) from account",Long.class);

}

将返回的结果封装成为类:

public void demo4(){

Account account=jdbcTemplate.queryForObject("select * from account where id=?", new MyRowMapper(),5);

}

其中:

class MyRowMapper implements RowMapper{

@Override

public Account mapRow(ResultSet rs, int rowNum) throws SQLException {

Account account=new Account();

account.setId(rs.getInt("id"));

account.setName(rs.getString("name"));

account.setMoney(rs.getDouble("money"));

return account;

}

}

【Spring的事务管理】

(一)、事务

事务是指逻辑上的一组操作,组成这组操作的各个单元,要么全部成功,要么全部失败。

具有四个特性:

1、原子性:事务不可分

2、一致性:事务执行前后资料完整性保持一致

3、隔离性:一个事务的执行不应该受到其他事务干扰

4、永续性:一旦事务结束,资料就持久化到数据库

如果不考虑隔离性会引发安全性问题:

1、读问题:

2、脏读:一个事务读到另一个事务未提交的资料

3、不可重复读:一个事务读到另一个事务已经提交的 update 资料,导致一个事务中多次查询结果不一致

4、幻读:一个事务读到另一个事务已经提交的 insert 资料,导致一个事务中多次查询结果不一致

5、写问题:丢失更新

解决读问题:设定事务隔离级别

1、Read uncommitted: 未提交读,无法解决任何读问题

2、Read committed: 已提交读,解决脏读问题

3、Repeatable read: 重复读,解决脏读和不可重复读问题

4、Serializable:序列化,解决所有读问题

(二)、事务管理API

1、PlatformTransactionManager: 平台事务管理器

这是一个界面,拥有多个不同的实现类,如 DataSourceTransactionManager 底层使用了JDBC 管理事务; HibernateTransactionManager 底层使用了 Hibernate 管理事务。

2、TransactionDefinition: 事务定义资讯

用于定义事务的相关资讯,如隔离级别、超时资讯、传播行为、是否只读等

3、TransactionStatus: 事务的状态

用于记录在事务管理过程中,事务的状态的物件。

上述API的关系: Spring 在进行事务管理的时候,首先平台事务管理器根据事务定义资讯进行事务管理,在事务管理过程当中,产生各种此状态,将这些状态资讯记录到事务状态的物件当中。

(三)、事务的传播行为

事务的传播行为主要解决业务层(Service)方法相互呼叫的问题,也就是不同的业务中存在不同的事务时,如何操作。

Spring 中提供了7种事务的传播行为,分为三类:

1、保证多个操作在同一个事务中

2、PROPAGATION_REQUIRED: B方法呼叫A方法,如果A中有事务,使用A中的事务并将B中的操作包含到该事务中;否则新建一个事务,将A和B中的操作包含进来。(预设)

3、PROPAGATION_SUPPORTS:如果A中有事务,使用A的事务;否则不使用事务

4、PROPAGATION_MANDATORY:如果A中有事务,使用A的事务;否则丢掷异常

保证多个操作不在同一个事务中

1、PROPAGATION_REQUIRES_NEW:如果A中有事务,将其挂起,建立新事务,只包含自身操作。否则,新建一个事务,只包含自身操作。

2、PROPAGATION_NOT_SUPPORTED:如果A中有事务,挂起,不使用事务。

3、PROPAGATION_NEVER:如果A中有事务,丢掷异常,也即不能用事务执行。

巢状事务

PROPAGATION_NESTED:如果A有事务,按照A的事务执行,执行完成后,设定一个储存点,然后执行B的操作。如果出现异常,可以回滚到最初状态或储存点状态。

(四)、例项

以转账为例,业务层的DAO层类如下:

public interface AccountDao {

public void outMoney(String from,Double money);

public void inMoney(String to,Double money);

}

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{

@Override

public void outMoney(String from, Double money) {

this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,from);

}

@Override

public void inMoney(String to, Double money) {

this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,to);

}

}

public interface AccountService {

public void transfer(String from,String to,Double money);

}

public class AccountServiceImpl implements AccountService {

private AccountDao accountDao;

public void setAccountDao(AccountDao accountDao) {

this.accountDao = accountDao;

}

@Override

public void transfer(String from, String to, Double money) {

accountDao.outMoney(from, money);

accountDao.inMoney(to, money);

}

}

在xml中进行类的配置:

(五)、事务管理1: 程式设计式事务管理

1、配置平台事务管理器

2、配置事务管理模板类

3、在业务层注入事务管理模板

4、编码实现事务管理

//ServiceImpl类中:

private TransactionTemplate transactionTemplate;

@Override

public void transfer(String from, String to, Double money) {

transactionTemplate.execute(new TransactionCallbackWithoutResult() {

@Override

protected void doInTransactionWithoutResult(TransactionStatus arg0) {

accountDao.outMoney(from, money);

accountDao.inMoney(to, money);

}

});

}

(六)、宣告式事务管理(配置实现,基于AOP思想)

1、XML 方式的宣告式事务管理

配置事务管理器

配置事务通知

配置aop事务

注解方式

1、配置事务管理器,和上方一致

2、开启事务管理的注解:

3、在使用事务的类上新增一个注解@Transactional

【粉丝福利】:

《架构师资料》领取方法

关注+转发,然后私信关键词 【架构】,即可获取。