@EnableConfigurationProperties注解详解,源码

2019-09-19 11:46:45

参考地址

用springboot开发的过程中,我们会用到@ConfigurationProperties注解,主要是用来把properties或者yml配置文件转化为bean来使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。 如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的,当然在@ConfigurationProperties加入注解的类上加@Component也可以使交于springboot管理。

举个栗子

第一步:创建一个类TestConfigurationProperties

@ConfigurationProperties(prefix = "properties")public class TestConfigurationProperties {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }}复制代码

注意:得加上set和get方法

第二步:创建TestAutoConfiguration类

@Configuration@EnableConfigurationProperties(TestConfigurationProperties.class)public class TestAutoConfiguration {

    private TestConfigurationProperties testConfigurationProperties;

    public TestAutoConfiguration(TestConfigurationProperties testConfigurationProperties) {
        this.testConfigurationProperties = testConfigurationProperties;
    }

    @Bean
    public User user(){
        User user = new User();
        user.setName(testConfigurationProperties.getName());
        return user;
    }}复制代码

注意:得创建一个有参构造方法

第三步:配置文件加入属性

properties.name=test
复制代码

第四步:跑一下,打印出User这个类

@RestController@RequestMapping("/api/test")@Slf4jpublic class TestController {
    @Autowired
    TestConfigurationProperties testConfigurationProperties;

    @Autowired
    User user;

    @RequestMapping(value = "/testConfigurationProperties")
    public String testConfigurationProperties() {
        log.info("test testConfigurationProperties.............{}", testConfigurationProperties.getName());
        log.info("user:{}", user);
        return "SUCCESS";
    }}复制代码

控制台输出:

2019-04-21/16:11:36.638||||||||^_^|[http-nio-8088-exec-1] INFO  com.stone.zplxjj.controller.TestController 37 - test testConfigurationProperties.............test2019-04-21/16:11:36.639||||||||^_^|[http-nio-8088-exec-1] INFO  com.stone.zplxjj.controller.TestController 38 - user:User(id=null, name=test)复制代码

@EnableConfigurationProperties是怎么加载的

通过查看@EnableConfigurationProperties的注解:

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Import(EnableConfigurationPropertiesImportSelector.class)public @interface EnableConfigurationProperties {

	/**
	 * Convenient way to quickly register {@link ConfigurationProperties} annotated beans
	 * with Spring. Standard Spring Beans will also be scanned regardless of this value.
	 * @return {@link ConfigurationProperties} annotated beans to register
	 */
	Class<?>[] value() default {};}复制代码

通过分析自动配置可以知道,肯定是这个类EnableConfigurationPropertiesImportSelector起的作用:

private static final String[] IMPORTS = {
			ConfigurationPropertiesBeanRegistrar.class.getName(),
			ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() };

	@Override
	public String[] selectImports(AnnotationMetadata metadata) {
		return IMPORTS;
	}复制代码

selectImports方法返回了这两个类:ConfigurationPropertiesBeanRegistrar和ConfigurationPropertiesBindingPostProcessorRegistrar,是何时加载的,我们只需要看这个类ConfigurationPropertiesBeanRegistrar即可:

public static class ConfigurationPropertiesBeanRegistrar
			implements ImportBeanDefinitionRegistrar {

		@Override
		public void registerBeanDefinitions(AnnotationMetadata metadata,
				BeanDefinitionRegistry registry) {
			getTypes(metadata).forEach((type) -> register(registry,
					(ConfigurableListableBeanFactory) registry, type));
		}
        //找到加入这个注解@EnableConfigurationProperties里面的value值,其实就是类class
		private List<Class<?>> getTypes(AnnotationMetadata metadata) {
			MultiValueMap<String, Object> attributes = metadata					.getAllAnnotationAttributes(
							EnableConfigurationProperties.class.getName(), false);
			return collectClasses((attributes != null) ? attributes.get("value")
					: Collections.emptyList());
		}

		private List<Class<?>> collectClasses(List<?> values) {
			return values.stream().flatMap((value) -> Arrays.stream((Object[]) value))
					.map((o) -> (Class<?>) o).filter((type) -> void.class != type)
					.collect(Collectors.toList());
		}
      //注册方法:根据找到的类名name和type,将加入注解@ConfigurationProperties的类加入spring容器里面
		private void register(BeanDefinitionRegistry registry,
				ConfigurableListableBeanFactory beanFactory, Class<?> type) {
			String name = getName(type);
			if (!containsBeanDefinition(beanFactory, name)) {
				registerBeanDefinition(registry, name, type);
			}
		}
    //找到加入注解@ConfigurationProperties的类的名称,加入一定格式的拼接
		private String getName(Class<?> type) {
			ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type,
					ConfigurationProperties.class);
			String prefix = (annotation != null) ? annotation.prefix() : "";
			return (StringUtils.hasText(prefix) ? prefix + "-" + type.getName()
					: type.getName());
		}

		private boolean containsBeanDefinition(
				ConfigurableListableBeanFactory beanFactory, String name) {
			if (beanFactory.containsBeanDefinition(name)) {
				return true;
			}
			BeanFactory parent = beanFactory.getParentBeanFactory();
			if (parent instanceof ConfigurableListableBeanFactory) {
				return containsBeanDefinition((ConfigurableListableBeanFactory) parent,
						name);
			}
			return false;
		}

		private void registerBeanDefinition(BeanDefinitionRegistry registry, String name,
				Class<?> type) {
			assertHasAnnotation(type);
			GenericBeanDefinition definition = new GenericBeanDefinition();
			definition.setBeanClass(type);
			registry.registerBeanDefinition(name, definition);
		}

		private void assertHasAnnotation(Class<?> type) {
			Assert.notNull(
					AnnotationUtils.findAnnotation(type, ConfigurationProperties.class),
					() -> "No " + ConfigurationProperties.class.getSimpleName()
							+ " annotation found on  '" + type.getName() + "'.");
		}

	}复制代码

结语

另外还有这个类:ConfigurationPropertiesBindingPostProcessorRegistrar,刚刚没有分析,看了下源码,其实他做的事情就是将配置文件当中的属性值赋予到加了@ConfigurationProperties的注解的类的属性上,具体就不分析了,有兴趣自己可以阅读,入口知道了,就简单了


  • 2019-09-03 23:09:17

    Linux下静态库(.a)和动态库(.so) 的生成与使用以及区别

    静态库在程序编译时会被连接到目标代码中,程序运行时将不再需要该静态库。 动态库在程序编译时并不会被连接到目标代码中,而是在程序运行是才被载入,因此在程序运行时还需要动态库存在。

  • 2019-09-03 23:19:12

    ./configure 的配置和用法

    Linux环境下的软件安装,并不是一件容易的事情;如果通过源代码编译后在安装,当然事情就更为复杂一些;现在安装各种软件的教程都非常普遍;但万变不离其中,对基础知识的扎实掌握,安装各种软件的问题就迎刃而解了。Configure脚本配置工具就是基础之一,它是autoconf的工具的基本应用。

  • 2019-09-04 16:24:17

    Ubuntu apt-get更换为阿里源

    ​进入阿里巴巴开源镜像页面,找到ubuntu,点击后面的帮助,可以看到类似下面的介绍,加入就好。切记下面的第三步。

  • 2019-09-04 16:32:56

    Ubuntu tar 解压缩命令详解

    tar 解压缩命令详解,这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用其中一个。下面的参数是根据需要在压缩或解压档案时可选的。

  • 2019-09-04 16:50:35

    CMake入门笔记

    Make是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的automake。只是 CMake 的组态档取名为 CMakeLists.txt。Cmake 并不直接建构出最终的软件,而是产生标准的建构档(如 Unix 的 Makefile 或 Windows Visual C++ 的 projects/workspaces),然后再依一般的建构方式使用。这使得熟悉某个集成开发环境(IDE)的开发者可以用标准的方式建构他的软件,这种可以使用各平台的原生建构系统的能力是 CMake 和 SCons 等其他类似系统的区别之处。

  • 2019-09-05 20:51:15

    在Android上使用FFmpeg压缩视频

    libavcodec-提供了更加全面的编解码实现的合集 libavformat-提供了更加全面的音视频容器格式的封装和解析以及所支持的协议 libavutil-提供了一些公共函数 libavfilter-提供音视频的过滤器,如视频加水印、音频变声等 libavdevice-提供支持众多设备数据的输入与输出,如读取摄像头数据、屏幕录制 libswresample,libavresample-提供音频的重采样工具 libswscale-提供对视频图像进行色彩转换、缩放以及像素格式转换,如图像的YUV转换 libpostproc-多媒体后处理器

  • 2019-09-05 20:54:21

    在Android 中使用FFmpeg命令

    到这里就可以运行FFmpeg命令了。一直我也是这样使用,但是我在做这个项目Cut的时候发现连续调用多次FFmpeg命令会报错(在项目需要,先改变分镜头的速度,再合成视频)。 为什么会这样的呢?