[SpringBoot] 利用spring.factories机制加载Bean

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/my_momo_csdn/article/details/83657067

通常我们需要注册一个bean会使用注解的形式,比如@Component注解,但是在阅读源码的时候我们发现一些bean上面并没有 该注解或者其他注册为bean的注解,甚至没有任何注解,这就纳闷了,仔细发现它用到了spring.factories机制。 在zuul的源码阅读中,找到了org.springframework.cloud.netflix.zuul.filters包下有很多已经实现好的过滤器,这些都是zuul组件进行路由转发的关键,但是并没有采用注解,如下:

package org.springframework.cloud.netflix.zuul.filters.pre;

public class DebugFilter extends ZuulFilter {

	private static final DynamicBooleanProperty ROUTING_DEBUG = DynamicPropertyFactory
			.getInstance().getBooleanProperty(ZuulConstants.ZUUL_DEBUG_REQUEST, false);

	private static final DynamicStringProperty DEBUG_PARAMETER = DynamicPropertyFactory
			.getInstance().getStringProperty(ZuulConstants.ZUUL_DEBUG_PARAMETER, "debug");

  ...省略..

}
     PS:DebugFilter 过滤器并且有添加任何注解

找到该包下的META-INF下面的spring.factories文件,发现有如下的一行:
org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration,
找到ZuulServerAutoConfiguration这个自动配置类,代码如下:

@Configuration
@EnableConfigurationProperties({ ZuulProperties.class })
@ConditionalOnClass(ZuulServlet.class)
@ConditionalOnBean(ZuulServerMarkerConfiguration.Marker.class)
// Make sure to get the ServerProperties from the same place as a normal web app would
@Import(ServerPropertiesAutoConfiguration.class)
public class ZuulServerAutoConfiguration {
    ...省略..
	@Bean
	public DebugFilter debugFilter() {
		return new DebugFilter();
	}
	 ...省略..
}

这里面通过@Bean注解注册了很多bean,其中就有DebugFilter,当然还有很多其他的过滤器和相关的组件,到这步如果还想知道为什么这样做就可以将里面的bean注册,就需要探究spring.facories机制的原理和加载时机了。这就不在本文详述,这里主要是介绍这一种方式.

猜你喜欢

转载自blog.csdn.net/my_momo_csdn/article/details/83657067