Spring @Value注解解析源码

前言

我们使用spring最常用的属性注入方式就是@Value,而要注入的属性我们一般都配置在配置文件application.properties中,上文讲解了配置文件application.properties加载到spring环境变量environment的过程

这一篇就来讲解一下spring是如何把environment中的属性值使用@Value注入到字段中的

源码解析

从springboot启动类开始

public static void main(String[] args) {
   
   
        SpringApplication.run(ConsumerApplication.class, args);
    }
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
   
   
		return run(new Class<?>[] {
   
    primarySource }, args);
	}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
   
   
		return new SpringApplication(primarySources).run(args);
	}
public ConfigurableApplicationContext run(String... args) {
   
   
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
   
   
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] {
   
    ConfigurableApplicationContext.class }, context);
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			// 核心
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
   
   
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
   
   
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
   
   
			listeners.running(context);
		}
		catch (Throwable ex) {
   
   
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

看refreshContext方法,是初始化上下文的

private void refreshContext(ConfigurableApplicationContext context) {
   
   
		if (this.registerShutdownHook) {
   
   
			try {
   
   
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
   
   
				// Not allowed in some environments.
			}
		}
		// 核心
		refresh((ApplicationContext) context);
	}

继续refresh

@Deprecated
	protected void refresh(ApplicationContext applicationContext) {
   
   
		Assert.isInstanceOf(ConfigurableApplicationContext.class, applicationContext);
		refresh((ConfigurableApplicationContext) applicationContext);
	}
protected void refresh(ConfigurableApplicationContext applicationContext) {
   
   
		applicationContext.refresh();
	}

继续,这里根据环境默认会进入servlet相关的上下文类ServletWebServerApplicationContext

@Override
	public final void refresh() throws BeansException, IllegalStateException {
   
   
		try {
   
   
			super.refresh();
		}
		catch (RuntimeException ex) {
   
   
			WebServer webServer = this.webServer;
			if (webServer != null) {
   
   
				webServer.stop();
			}
			throw ex;
		}
	}

进入AbstractApplicationContext的refresh

@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.
			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.
				// 核心1
				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();
			}
		}
	}

这个方法很长,属于spring的一个关键方法,既然是要解析@Value注解,那么首先肯定要初始化实例bean才行,核心1的finishBeanFactoryInitialization就是和实例化有关的

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.
		// 核心1
		beanFactory.preInstantiateSingletons();
	}

核心1处看注释和方法名,看上去像是预处理单例bean的

@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...
		// 核心1
		for (String beanName : beanNames) {
   
   
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
   
   
				if (isFactoryBean(beanName)) {
   
   
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
   
   
						FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
   
   
							isEagerInit = AccessController.
Spring 框架在处理注解时,尤其是支持 Java 8 引入的 `@Repeatable` 注解机制上,使用了反射和注解处理工具来解析重复注解。下面我们将从源码层面详细分析 Spring 是如何解析 `@Repeatable` 注解的。 --- ### 回答问题 #### Spring 内部是如何解析 `@Repeatable` 注解的? **简要流程:** 1. **Java 原生支持:** - Java 8 开始允许一个注解被重复使用在同一元素上,前提是该注解使用了 `@Repeatable` 元注解,并指定了一个“容器注解”。 - 示例: ```java @Repeatable(Roles.class) public @interface Role { String value(); } public @interface Roles { Role[] value(); } ``` 2. **Spring 的 `AnnotatedElementUtils` 工具类:** - Spring 提供了 `org.springframework.core.annotation.AnnotatedElementUtils` 来统一处理各种注解(包括重复注解)。 - 这个类封装了复杂的查找逻辑,能够自动识别嵌套注解、组合注解、重复注解等。 3. **获取所有重复注解:** - 使用 `AnnotatedElementUtils.getMergedAnnotations()` 或 `getRepeatableAnnotations()` 方法可以获取所有的 `@Repeatable` 注解实例。 - 示例代码: ```java Method method = clazz.getMethod("someMethod"); List<Role> roles = AnnotatedElementUtils.getRepeatableAnnotations(method, Role.class, Roles.class); ``` 4. **核心实现:`MergedAnnotations` 和 `RepeatableContainers`:** - `MergedAnnotations` 是 Spring 5 中引入的新 API,用于统一处理注解的合并、继承、重复等行为。 - `RepeatableContainers` 负责管理 `@Repeatable` 注解与它们的容器之间的关系。 5. **底层原理:** - Spring 会检查目标注解是否带有 `@Repeatable`。 - 如果有,则通过反射获取其容器注解,并从容器中提取出所有实际的注解实例。 - 同时,它还支持注解的层级结构(比如注解上的注解也可能是 `@Repeatable`)。 6. **示例源码片段:** - 在 `AnnotatedElementUtils` 中: ```java public static <A extends Annotation> List<A> getRepeatableAnnotations( AnnotatedElement element, Class<A> annotationType, Class<? extends Annotation> containerType) { return MergedAnnotations.from(element).get(annotationType).asList(); } ``` - `MergedAnnotations` 内部会自动识别并展开 `@Repeatable` 注解。 --- ### 解释说明: - `@Repeatable` 是 Java 8 引入的元注解,允许在同一个地方多次使用相同的注解。 - Spring 框架为了兼容性和扩展性,设计了一整套注解处理机制,其中对 `@Repeatable` 的处理是自动完成的。 - Spring 不直接使用 Java 的 `getAnnotationsByType()`,而是封装了自己的处理逻辑,以支持更复杂的场景(如组合注解、条件注解、别名等)。 - Spring 的 `MergedAnnotations` 提供了比原生 Java 更强大的功能,例如: - 支持注解继承(如方法上的注解会继承类级别的注解) - 支持注解别名(alias for attributes) - 支持组合注解(composed annotations) --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值