当前位置: 首页 > wzjs >正文

天津企业网站做推广可以上那些网站

天津企业网站,做推广可以上那些网站,电信网络运营商,手机上怎么自己设计房子单例模式 在Spring Boot中,单例模式是默认的Bean作用域,Spring容器会保证每个单例Bean仅有一个实例。以DefaultSingletonBeanRegistry类为例,它是Spring容器实现单例模式的关键类。 以下是简化的源码分析: public class Defaul…

单例模式

在Spring Boot中,单例模式是默认的Bean作用域,Spring容器会保证每个单例Bean仅有一个实例。以DefaultSingletonBeanRegistry类为例,它是Spring容器实现单例模式的关键类。

以下是简化的源码分析:

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {// 用于存储单例Bean的缓存private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);@Overridepublic Object getSingleton(String beanName) {return getSingleton(beanName, true);}protected Object getSingleton(String beanName, boolean allowEarlyReference) {// 从单例缓存中获取BeanObject singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {synchronized (this.singletonObjects) {singletonObject = this.earlySingletonObjects.get(beanName);if (singletonObject == null && allowEarlyReference) {ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);if (singletonFactory != null) {singletonObject = singletonFactory.getObject();this.earlySingletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);}}}}return singletonObject;}protected void addSingleton(String beanName, Object singletonObject) {synchronized (this.singletonObjects) {// 将单例Bean添加到缓存中this.singletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);}}
}

在上述代码里,singletonObjects这个Map用于存储单例Bean实例。getSingleton方法会先从缓存里查找Bean实例,若不存在则创建;addSingleton方法会把创建好的单例Bean添加到缓存中。

工厂模式

BeanFactory是Spring框架里工厂模式的核心体现,它负责创建和管理Bean实例。AbstractBeanFactoryBeanFactory的一个重要抽象实现类。

以下是部分源码分析:

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {@Overridepublic Object getBean(String name) throws BeansException {return doGetBean(name, null, null, false);}protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException {String beanName = transformedBeanName(name);Object bean;// 从缓存中获取单例BeanObject 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 {// 创建Bean实例if (isPrototypeCurrentlyInCreation(beanName)) {throw new BeanCurrentlyInCreationException(beanName);}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 {// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}}if (!typeCheckOnly) {markBeanAsCreated(beanName);}try {RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current 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);getBean(dep);}}// Create bean instance.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;}
}

doGetBean方法会依据Bean的名称获取对应的Bean实例。要是缓存里没有,就会调用createBean方法来创建新的实例。

代理模式

Spring AOP借助代理模式达成面向切面编程。JdkDynamicAopProxy是基于JDK动态代理实现的AOP代理类。

以下是简化的源码分析:

final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {private final AdvisedSupport advised;public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {Assert.notNull(config, "AdvisedSupport must not be null");if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {throw new AopConfigException("No advisors and no TargetSource specified");}this.advised = config;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {MethodInvocation invocation;Object oldProxy = null;boolean setProxyContext = false;TargetSource targetSource = this.advised.getTargetSource();Object target = null;try {if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {// The target does not implement the equals(Object) method itself.return equals(args[0]);}else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {// The target does not implement the hashCode() method itself.return hashCode();}else if (method.getDeclaringClass() == DecoratingProxy.class) {// There is only getDecoratedClass() declared -> dispatch to proxy config.return AopProxyUtils.ultimateTargetClass(this.advised);}else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&method.getDeclaringClass().isAssignableFrom(Advised.class)) {// Service invocations on ProxyConfig with the proxy config...return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);}Object retVal;if (this.advised.exposeProxy) {// Make invocation available if necessary.oldProxy = AopContext.setCurrentProxy(proxy);setProxyContext = true;}// Get as late as possible to minimize the time we "own" the target,// in case it comes from a pool.target = targetSource.getTarget();Class<?> targetClass = (target != null ? target.getClass() : null);// Get the interception chain for this method.List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);// Check whether we have any advice. If we don't, we can fallback on direct// reflective invocation of the target, and avoid creating a MethodInvocation.if (chain.isEmpty()) {// We can skip creating a MethodInvocation: just invoke the target directly// Note that the final invoker must be an InvokerInterceptor so we know it does// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);}else {// We need to create a method invocation...invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);// Proceed to the joinpoint through the interceptor chain.retVal = invocation.proceed();}// Massage return value if necessary.Class<?> returnType = method.getReturnType();if (retVal != null && retVal == target &&returnType != Object.class && returnType.isInstance(proxy) &&!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {// Special case: it returned "this" and the return type of the method// is type-compatible. Note that we can't help if the target sets// a reference to itself in another returned object.retVal = proxy;}else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);}return retVal;}finally {if (target != null && !targetSource.isStatic()) {// Must have come from TargetSource.targetSource.releaseTarget(target);}if (setProxyContext) {// Restore old proxy.AopContext.setCurrentProxy(oldProxy);}}}
}

invoke方法是代理对象的核心方法,在调用目标方法时,会先获取拦截器链,接着按顺序执行拦截器逻辑,最后调用目标方法。

观察者模式

Spring的事件驱动机制运用了观察者模式。SimpleApplicationEventMulticaster是事件广播器的实现类。

以下是简化的源码分析:

public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {@Overridepublic void multicastEvent(ApplicationEvent event) {multicastEvent(event, resolveDefaultEventType(event));}@Overridepublic void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));Executor executor = getTaskExecutor();for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {if (executor != null) {executor.execute(() -> invokeListener(listener, event));}else {invokeListener(listener, event);}}}protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {ErrorHandler errorHandler = getErrorHandler();if (errorHandler != null) {try {doInvokeListener(listener, event);}catch (Throwable err) {errorHandler.handleError(err);}}else {doInvokeListener(listener, event);}}private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {try {listener.onApplicationEvent(event);}catch (ClassCastException ex) {String msg = ex.getMessage();if (msg == null || matchesClassCastMessage(msg, event.getClass())) {// Possibly a lambda-defined listener which we could not resolve the generic event type for// -> let's suppress the exception and just log a debug message.Log logger = LogFactory.getLog(getClass());if (logger.isTraceEnabled()) {logger.trace("Non-matching event type for listener: " + listener, ex);}}else {throw ex;}}}
}

multicastEvent方法会把事件广播给所有注册的监听器,监听器实现了ApplicationListener接口,在onApplicationEvent方法里处理事件。

模板方法模式

JdbcTemplate是Spring JDBC模块里模板方法模式的典型应用。

以下是简化的源码分析:

public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {@Overridepublic <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {Assert.notNull(sql, "SQL must not be null");Assert.notNull(rse, "ResultSetExtractor must not be null");if (logger.isDebugEnabled()) {logger.debug("Executing SQL query [" + sql + "]");}class QueryStatementCallback implements StatementCallback<T>, SqlProvider {@Overridepublic T doInStatement(Statement stmt) throws SQLException {ResultSet rs = null;try {rs = stmt.executeQuery(sql);return rse.extractData(rs);}finally {JdbcUtils.closeResultSet(rs);}}@Overridepublic String getSql() {return sql;}}return execute(new QueryStatementCallback());}@Overridepublic <T> T execute(StatementCallback<T> action) throws DataAccessException {Assert.notNull(action, "Callback object must not be null");Connection con = DataSourceUtils.getConnection(obtainDataSource());Statement stmt = null;try {stmt = con.createStatement();applyStatementSettings(stmt);T result = action.doInStatement(stmt);handleWarnings(stmt);return result;}catch (SQLException ex) {// Release Connection early, to avoid potential connection pool deadlock// in the case when the exception translator hasn't been initialized yet.String sql = getSql(action);JdbcUtils.closeStatement(stmt);stmt = null;DataSourceUtils.releaseConnection(con, getDataSource());con = null;throw getExceptionTranslator().translate("StatementCallback", sql, ex);}finally {JdbcUtils.closeStatement(stmt);DataSourceUtils.releaseConnection(con, getDataSource());}}
}

query方法定义了查询操作的模板,把具体的结果集处理逻辑委托给ResultSetExtractorexecute方法则封装了通用的数据库连接和语句执行逻辑。


文章转载自:

http://BDke8EhD.bswnf.cn
http://y5fQIe41.bswnf.cn
http://v5q0OePB.bswnf.cn
http://F9RC5ix7.bswnf.cn
http://5eQRDuhi.bswnf.cn
http://kCqtBTQS.bswnf.cn
http://dmmcpbXw.bswnf.cn
http://N6fAOFPp.bswnf.cn
http://ToEjwqTJ.bswnf.cn
http://yfHsmm5k.bswnf.cn
http://84BQOgP9.bswnf.cn
http://ercJJ5T9.bswnf.cn
http://RXMxmyYD.bswnf.cn
http://UldGDSKN.bswnf.cn
http://1aXKCYpe.bswnf.cn
http://xevpJRPW.bswnf.cn
http://f98jKafc.bswnf.cn
http://C0bks7F2.bswnf.cn
http://Kzhj0MKh.bswnf.cn
http://bIFVperw.bswnf.cn
http://rA4NwHuk.bswnf.cn
http://fORyQFCr.bswnf.cn
http://CC9mxdEx.bswnf.cn
http://gIOxQFXE.bswnf.cn
http://IDNStGQj.bswnf.cn
http://S2mTNoHc.bswnf.cn
http://hq4O6Cud.bswnf.cn
http://uiRPPtyF.bswnf.cn
http://ZUFJJYsN.bswnf.cn
http://xDzYja5S.bswnf.cn
http://www.dtcms.com/wzjs/671788.html

相关文章:

  • 网站重新安装学校网站手机站的建设方案
  • 哪种网站名称容易通过备案审核济南网站建设有限公司
  • 作风建设网站南京电信网站空间扩容
  • 建设网站导航怎么盈利网站开发接入支付宝
  • 擦边球网站怎么做门户一号wordpress 主题下载
  • 机关门户网站建设意义绵阳住房和城乡建设厅网站
  • 二维码生成器网站视频logo免费生成网站软件
  • wordpress备份网站做网站是什么行业
  • 上海制作网站公司网站广东新闻联播片头
  • 花钱做网站注意些什么织梦网站程序模板
  • 网站建设的三要素诸暨哪些公司可以制作网站
  • 网站备案多久古镇营销型网站建设
  • 贵州建设网老网站如何注册公司地址定位
  • 自助建站系统官网网站开发建设方案
  • 怎么网站搜索排名优化站长之家seo综合
  • 企业网站推广优化招远做网站公司
  • 温州做网站哪里好网页设计素材图片怎么获取
  • 网站优化软件方案网站 服务器 虚拟主机
  • 北京工程建设交易中心网站百度下拉框推广网站
  • 什么是做自己的网站英国搜索引擎
  • 屏山县建设局网站有机玻璃东莞网站建设技术支持
  • 怎么用网吧电脑做网站服务器吗免费域名注册万网
  • 做的好的h游戏下载网站国外网站建设素材
  • 昆山住房和城乡建设局网站旅游网站介绍怎么写
  • 网站建设找a金手指wordpress 使用七牛云
  • phpcms 关闭网站邢台招聘信息网
  • 网站怎么做关键词优化牡丹江整站优化
  • 北京网站设计网站公司新开的网页游戏大全
  • 广西南宁网站建设有限公司中国建筑工程考试网
  • 四川住房建设厅网站首页yellow的视频播放