代码命名之 Spring

发布于 2024-05-19
开发中对于业务功能开发一般我们命令都是 Controller, Service, ServiceImpl, Mapper, Repository 之类的,但是对于一些特殊的功能我们需要自定义命名,这里我们参考下 Spring 源码中的命名规范。 初始化 Initializer

开发中对于业务功能开发一般我们命令都是 Controller, Service, ServiceImpl, Mapper, Repository 之类的,但是对于一些特殊的功能我们需要自定义命名,这里我们参考下 Spring 源码中的命名规范。

初始化 Initializer

Spring 中的初始化类一般都是以 Initializer 结尾,如 ApplicationContextInitializer, BeanFactoryPostProcessor, BeanPostProcessor 等。

@FunctionalInterface
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

	/**
	 * Initialize the given application context.
	 * @param applicationContext the application to configure
	 */
	void initialize(C applicationContext);

}

管理器 Manager

Spring 中的管理器一般都是以 Manager 结尾,如 TransactionManager, CacheManager, DataSourceTransactionManager 等。

管理器可以理解为对某一类资源的管理,如事务管理器,缓存管理器等。

public interface TransactionManager
{
    /**
     *  Starts a new transaction, and associate it with the calling thread.
     *
     *  @throws NotSupportedException If the calling thread is already
     *          associated with a transaction, and nested transactions are
     *          not supported.
     *  @throws SystemException If the transaction service fails in an
     *          unexpected way.
     */
    public void begin() throws NotSupportedException, SystemException;

    /**
     *  Commit the transaction associated with the calling thread.
     *
     *  @throws RollbackException If the transaction was marked for rollback
     *          only, the transaction is rolled back and this exception is
     *          thrown.
     *  @throws IllegalStateException If the calling thread is not associated
     *          with a transaction.
     *  @throws SystemException If the transaction service fails in an
     *          unexpected way.
     *  @throws HeuristicMixedException If a heuristic decision was made and
     *          some some parts of the transaction have been committed while
     *          other parts have been rolled back.
     *  @throws HeuristicRollbackException If a heuristic decision to roll
     *          back the transaction was made.
     *  @throws SecurityException If the caller is not allowed to commit this
     *          transaction.
     */
    public void commit() throws RollbackException, HeuristicMixedException,
                   HeuristicRollbackException, SecurityException,
                   IllegalStateException, SystemException;

   // ......省略其他方法
}

处理器

Spring 中对处理器有两种命令方式:

  • 一种是以 Handler 结尾,如 HandlerInterceptor, HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler 等。
  • 另一种是以 Processor 结尾,如 BeanPostProcessor, BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor 等。

这两种的区别我个人理解是:

  • Handler 用的比较多,一般是对特定类型或事件进行处理,多用于责任链模式中。
  • Processor 一般表示对特定阶段做处理,如预处理,后处理等。

Processor

Spring 中常见的 ProcessorBeanPostProcessor, BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor 等。

如下面的 BeanPostProcessor 接口用于提供在 Bean 初始化前后进行一些处理的能力。

public interface BeanPostProcessor {

	/**
	 * Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 */
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
	 * instance and the objects created by the FactoryBean (as of Spring 2.0). The
	 * post-processor can decide whether to apply to either the FactoryBean or created
	 * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
	 * <p>This callback will also be invoked after a short-circuiting triggered by a
	 * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
	 * in contrast to all other {@code BeanPostProcessor} callbacks.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 * @see org.springframework.beans.factory.FactoryBean
	 */
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}

Handler

Spring 中常见的 HandlerHandlerInterceptor, HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler 等。

如下面的 HandlerMethodReturnValueHandler 接口用于处理方法返回值。

public interface HandlerMethodReturnValueHandler {

	/**
	 * Whether the given {@linkplain MethodParameter method return type} is
	 * supported by this handler.
	 * @param returnType the method return type to check
	 * @return {@code true} if this handler supports the supplied return type;
	 * {@code false} otherwise
	 */
	boolean supportsReturnType(MethodParameter returnType);

	/**
	 * Handle the given return value by adding attributes to the model and
	 * setting a view or setting the
	 * {@link ModelAndViewContainer#setRequestHandled} flag to {@code true}
	 * to indicate the response has been handled directly.
	 * @param returnValue the value returned from the handler method
	 * @param returnType the type of the return value. This type must have
	 * previously been passed to {@link #supportsReturnType} which must
	 * have returned {@code true}.
	 * @param mavContainer the ModelAndViewContainer for the current request
	 * @param webRequest the current request
	 * @throws Exception if the return value handling results in an error
	 */
	void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception;

持有者 Holder

如果一个类是用来持有某个资源并包含一些操作资源的方法,那么这个类一般都是以 Holder 结尾,如 BeanDefinitionHolder, BeanFactoryPostProcessorBeanDefinitionRegistry, BeanDefinitionRegistryPostProcessorBeanDefinitionHolder 等。

BeanDefinitionHolder 为例,这个类用于持有 BeanDefinition 对象,还包含一些方法,如 matchesName 方法用于判断输入的指定名称是否匹配当前 Holder 持有的 BeanDefinition 对象名称或别名;getShortDescription 方法用于获取 BeanDefinition 的简短描述。

public class BeanDefinitionHolder implements BeanMetadataElement {

	private final BeanDefinition beanDefinition;

	private final String beanName;

	@Nullable
	private final String[] aliases;

	/**
	 * Create a new BeanDefinitionHolder.
	 * @param beanDefinition the BeanDefinition to wrap
	 * @param beanName the name of the bean, as specified for the bean definition
	 */
	public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName) {
		this(beanDefinition, beanName, null);
	}

	/**
	 * Create a new BeanDefinitionHolder.
	 * @param beanDefinition the BeanDefinition to wrap
	 * @param beanName the name of the bean, as specified for the bean definition
	 * @param aliases alias names for the bean, or {@code null} if none
	 */
	public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName, @Nullable String[] aliases) {
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");
		Assert.notNull(beanName, "Bean name must not be null");
		this.beanDefinition = beanDefinition;
		this.beanName = beanName;
		this.aliases = aliases;
	}

	/**
	 * Determine whether the given candidate name matches the bean name
	 * or the aliases stored in this bean definition.
	 */
	public boolean matchesName(@Nullable String candidateName) {
		return (candidateName != null && (candidateName.equals(this.beanName) ||
				candidateName.equals(BeanFactoryUtils.transformedBeanName(this.beanName)) ||
				ObjectUtils.containsElement(this.aliases, candidateName)));
	}

	/**
	 * Return a friendly, short description for the bean, stating name and aliases.
	 * @see #getBeanName()
	 * @see #getAliases()
	 */
	public String getShortDescription() {
		if (this.aliases == null) {
			return "Bean definition with name '" + this.beanName + "'";
		}
		return "Bean definition with name '" + this.beanName + "' and aliases [" + StringUtils.arrayToCommaDelimitedString(this.aliases) + ']';
	}

	/**
	 * Return a long description for the bean, including name and aliases
	 * as well as a description of the contained {@link BeanDefinition}.
	 * @see #getShortDescription()
	 * @see #getBeanDefinition()
	 */
	public String getLongDescription() {
		return getShortDescription() + ": " + this.beanDefinition;
	}
    
    // ......省略其他方法

}

执行器 Executor

执行器一般是用来执行某个任务的,多和线程池有关,Spring 中的执行器一般都是以 Executor 结尾,如 TaskExecutor, AsyncTaskExecutor, AsyncListenableTaskExecutor 等。

工具类 Utils

工具类一般包含一些静态方法,用于提供一些工具方法,Spring 中的工具类一般都是以 Utils 结尾,如 ClassUtils, BeanUtils, StringUtils 等。