Spring中常遇到的问题
什么是spring
Spring是分层的Java SE/EE的full-stack轻量级开源框架,以IOC(Inverse of Controll,反转控制)和AOP(Aspect Oriented Programming,面向切面编程)为内核,提供了表示层和持久层以及业务层事务管理等众多企业级开发技术,还能整合开源界诸多著名的第三方框架和类库,逐渐成为使用最多的企业级Java EE开发的首选开源框架。
1. Spring是如何对XXXService进行依赖注入的
概念:程序在运行时,希望给某个对象所依赖的对象赋值,就称作依赖注入(需要什么,传递什么,传递的任务由Spring完成)
依赖注入的方式 | 依赖注入的类型 |
setter方法注入 | 基本数据类型和spring类型 |
构造方法注入 | 普通POJO类型 |
注解注入 | 普通POJO类型 |
创建对应的Service接口和实现类
public interface AccountService
{
public Account findAccountById(Integer id) throws Exception;
public void transfer(Integer sourceId,Integer targetId,float money) throws Exception;
}
2. 注解的AOP配置遇到的异常
异常后需要执行的方法
package edu.xync.spring.util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/*
* 一个用于记录日志的类
*/
@Component("logger")
@Aspect//表示它是一个切面
public class Logger {
//切入点表达式
@Pointcut("execution(* edu.xync.spring.service.*.*(..))")
public void pt1()
{ }
//前置通知
public void beforePrintLog()
{
System.out.println("前置:Logger中的beforePrintLog()方法开始记录日志了------------");
}
//后置通知
public void afterReturningPrintLog()
{
System.out.println("后置:Logger中的afterReturningPrintLog()方法开始记录日志了------------");
}
//异常通知:异常发生后需要执行的方法
public void afterThrowingPrintLog()
{
System.out.println("异常:Logger中的afterThrowingPrintLog()方法开始记录日志了------------");
}
//最终通知:无论异常是否发生都会执行的方法
public void afterPrintLog()
{
System.out.println("最终:Logger中的afterPrintLog()方法开始记录日志了------------");
}
@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp)
{
Object rtValue=null;
try
{
this.beforePrintLog();
rtValue=pjp.proceed();
this.afterReturningPrintLog();
}
catch (Throwable e) {
e.printStackTrace();
this.afterThrowingPrintLog();
}
finally
{
this.afterPrintLog();
}
return rtValue;
}
}
3. Spring的声明式事务管理
事务的四大特性分别是:原子性、一致性、隔离性、持久性。
事务的隔离级别反应事务提交并发时的处理态度:
(1) READ UNCOMMITTED(读未提交数据): 允许事务读取未被其他事务提交的变更数据,会出现脏读、不可重复读和幻读问题。
(2)READ COMMITTED(读已提交数据):只允许事务读取已经被其他事务提交的变更数据,可避免脏读,仍会出现不可重复读和幻读问题。
(3)REPEATABLE READ(可重复读):确保事务可以多次从一个字段中读取相同的值,在此事务持续期间,禁止其他事务对此字段的更新,可以避免脏读和不可重复读,仍会出现幻读问题。
(4)SERIALIZABLE(序列化):确保事务可以从一个表中读取相同的行,在这个事务持续期间,禁止其他事务对该表执行插入、更新和删除操作,可避免所有并发问题,但性能非常低。
int ISOLATION_DEFAULT = -1; 默认采用数据库的隔离级
int ISOLATION_READ_UNCOMMITTED
= Connection.TRANSACTION_READ_UNCOMMITTED;
int ISOLATION_READ_CO