Spring
1.框架
高度抽取可重用代码的一种设计,具有高度的通用性(半成品软件)
- 书城: WebUtils. java; BaseServlet; Filter
- 打包: bookstore jar(工具类),commons-fileupload, commons-IO, commons-dbutils
- 框架:抽取成一种高度可重用的,比如:事务控制,强大的 servlet,项目中的一些工具。它是多个可重用模块的集合,形成一个某个领域的整体解决方案
2.Spring
容器(可以管理所有的组件/类)框架
核心关注:IOC和AOP
2.1.模块划分
Test:单元测试模块
Core Container:核心容器(IOC);黑色表示由哪些jar组成
AOP + Aspects:面向切面编程
Data Access/Integration:JDBC;ORM;TX
- OX(xml)M
Web:
- servlet:spring-web
- web:spring-webmvc
- portlet:spring-webmvc-portlet(开发web语应用的组件集成)
2.2.IOC(Inversion Of Control)
控制:控制资源的获取方式
- 主动式:需要资源自己主动创建
UserServlet{
//简单对象
private UserService userService = new UserService();
//复杂对象的创建是比较庞大的工程
}
- 被动式:资源获取不是自己主动创建,而是交给一个容器创建
UserServlet{
private UserService userService;
pubilc void test(){
userService.addUser();
}
}
反转:从主动的new资源变为被动的接受资源。
2.3.DI(Dependency Injection)
容器能直到哪个组件运行的时候,需要另外一个组件,容器通过反射的形式,将所需对象注入(利用反射给属性赋值)给需求对象
操作细节
@Scope(“prototype”)
- 多实例的
- 容器启动之前不会创建对象
- 在获取的时候创建bean
- 每次获取都会创建新的bean
@Scope(“single”)
- 单实例的;默认
- 在容器启动完成之前就已经创建好对象,保存在容器中
- 获取任意此对象都是容器启动之前创建的对象(单例)
静态工厂:工厂本身不用创建,通过静态方法调用:
- 对象 = 工厂类.工厂方法名();
实例工厂:工厂本身需要创建,
- 工厂类 工厂对象 = new 工厂类();
- 工厂对象.get对象(..);
@Autowired原理
@Autowired
private UserService userService;
先按照类型去容器中找到对应的组件:
UserService userService = ioc.getBean(UserService.class);
- 找到一个:找到就赋值
- 没找到:抛异常
找到多个:
按照变量名作为id继续匹配:
UserService(id = userService)
UserServiceExt(id = UserServiceExt)
- 匹配上:注入
没有匹配上:抛异常
解决办法:指定bean的id@Qualifier("userService")
- 匹配上:注入
没有匹配上:抛异常
@Autowired(required = false)
匹配不上,不抛出异常,不进行处理
方法上有Autowried:方法上的每个参数都会自动注入值
@Resource和@Autowried
@Resource:扩展性强(J2EE标准),切换容器框架依旧可以使用,而@Autowried不行
泛型依赖注入:注入一个组件时,它的泛型也是参考标准
2.3.1.源码
- IOC是一个容器
- 容器启动的时候创建所有单例对象
- 可以从容器中获取bean
ApplicationContext ioc = new ClassPathXmlApplicationContext();
ClassPathXmlApplicationContex
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
//*
this(new String[] {configLocation}, true, null);
}
↓
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
//*所有单例bean被实例化
refresh();
}
}
↓
AbstractApplicationContext
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//spring解析xml配置文件,将要创建的所有bean的配置信息保存
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//支持国际化功能
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//留给子类的方法
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//*初始化所有单例bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
↓
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
//*初始化所有单例bean
beanFactory.preInstantiateSingletons();
}
↓
DefaultListableBeanFactory
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
//按顺序创建bean
for (String beanName : beanNames) {
//根据bean的id获取bean的定义信息
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//此bean不是抽象的,是单例的,不是懒加载的
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//实现了FactoryBean接口的bean
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
//未实现FactoryBean接口的普通bean
else {
//*创建bean的细节
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
↓
AbstractBeanFactory
@Override
public Object getBean(String name) throws BeansException {
//*
return doGetBean(name, null, null, false);
}
↓
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//先从已注册的所有单例bean中看是否存在此bean
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//拿到当前bean创建之前需要的提前创建的bean。depends-on属性,若有就循环创建
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//创建bean实例
if (mbd.isSingleton()) {
//*
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
↓
DefaultSingletonBeanRegistry
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//先从
/** Cache of singleton objects: bean name to bean instance. */
//private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
//拿取bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//※利用反射创建bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
//添加创建的bean
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
创建好的对象最终会保存在DefaultSingletonBeanRegistry类的singletonObjects中
IOC容器之一:singletonObjects:保存单例bean
BeanFactory和ApplicationContext的区别
- ApplicationContext是BeanFactory的子接口;
- BeanFactory:bean工厂接口,负责创建bean实例;
- 最底层的接口
- ApplicationContext:容器接口,负责容器功能的实现;
- 留给人使用的ioc接口
- 可以基于BeanFactory创建好的对象,完成强大的容器功能
spring中最大的设计模式就是工厂模式
2.4.动态代理:
场景:计算器运行计算方法的时候进行日志记录
加日志记录:
- 直接编写在方法内部;不推荐,修改维护麻烦
- 日志记录:系统的辅助功能;
- 业务逻辑:(核心功能)
- 耦合
- 希望的是
- 业务逻辑:(核心功能)
- 日志模块:在核心功能运行期间,自己动态的加上
- 可以使用动态代理来将日志代码动态的在目标方法执行前后先进行执行;
package com.jjj.proxy;
import com.jjj.calculator.service.Calculator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Proxy;
import java.util.Arrays;
/**
* @author <a href="jinyu52370@163.com">JJJ</a>
* @date 2020/5/8 9:30
*/
public class CalculatorProxy {
private static Log log = LogFactory.getLog(CalculatorProxy.class);
public static Calculator getProxy(Calculator calculator){
return (Calculator) Proxy.newProxyInstance(
calculator.getClass().getClassLoader(),
calculator.getClass().getInterfaces(),
(proxy, method, args) -> {
log.info("The method "
+ method.getName()
+ "() begins with "
+ Arrays.toString(args));
Object result = null;
try {
result = method.invoke(calculator, args);
} catch (Exception e) {
log.info("The method "
+ method.getName()
+ "() throw exception: "
+ e.getCause());
}finally {
log.info("The method "
+ method.getName()
+ "() ends with "
+ result);
}
return result;
});
}
}
缺点:
- 写起来难
- 被代理对象必须实现接口(代理对象和被代理对象的唯一关联就是实现了同一个接口)
2.5.AOP
OOP:(Object Oriented Programming)面向对象编程
AOP:(Aspect Oriented Programming)面向切面编程
- 基于OOP基础之上新的编程思想
- 指在程序运行期间,将某段代码动态的切入到指定方法的指定位置进行运行的这种编程方式
通知方法的执行顺序:
try{
@Before
{
@Around(Before)
try{
method.invoke(obj, args);
@Around(Returning)
} catch(e){
@Around(Throwing)
} finally{
@Around(After)
}
}
@AfterReturning
} catch(e){
@AfterThrowing
} finally{
@After()
}
正常情况
异常情况
两个切面同时工作时,环绕只影响当前切面
切入点表达式写法:
固定格式:execution(访问权限符 返回值类型 方法全签名(参数表))
通配符:
- 匹配一个或多个字符:abc*z
- 匹配任意一个参数:abc(int, *)
- 匹配一层路径:com.pack.*.abc
- 访问权限符不能写,不写为匹配所有:但也只能匹配public,即public可写可不写
- ..
- 匹配任意个数和类型的参数:abc(..)
- 匹配任意层数的路径:com.pack..abc
最模糊:execution( .*(..))
最精确:execution(public Double CalculatorImpl.add(Double, Double)))
2.6.声明式事务
2.6.1.编程式事务
TransactionFilter{
try{
//获取连接
//设置非自动提交
chain.doFileter();
//提交
} catch(Exception e){
//回滚
} finally{
//关闭连接释放资源
}
}
2.6.2.声明式事务(基于AOP的环绕通知)
快速为某个方法添加事务:
- 配置事务管理器
- 开启基于注解的事务控制模式
- 给事务方法加注解
事务细节:
isolation
Isolation //事务的隔离级别
propagation
Propagation //事务的传播行为
异常分类
运行时/非检查异常:可以不处理;
默认回滚
编译时/检查异常:try-catch 或 throws;
默认不回滚
noRollbackFor
Class[] //可以让某些默认回滚的异常不回滚
noRollbackForclassName
String[] //String全类名
rollbackFor
Class[] //可以让某些默认不回滚的异常回滚
rollbackForclassName
String[] //String全类名
readonly
boolean //设置事务为只读事务
true //加快查询速度,无需进行commit等事务操作
timeout
int //事务超出指定执行时长(s)后自动终止并回滚
隔离级别
读未提交:脏读
读已提交:不可重复读
可重复读(快照读)
传播行为
REQUIRED:当前事务和大事务共用一个事务
- 当前事务的属性继承于大事务,比如timeout
- 将之前事务的connection传递给这个方法使用
REQUIRES_NEW:当前事务新开事务,若已经有事务,则将其挂起
- 使用新的connection
本类事务方法之间调用的是同一个事务
MulServiceProxy.mulTx(){
userServiceProxy.transfer();
userServiceProxy.updateMoneyByName();
}
//本类方法的嵌套调用就只是一个事务
UserServiceProxy.mulTx(){
transfer();
updateMoneyByName();
}