SpringBoot】 SpringBoot自动装配原理?

2020-12-09 16:57发布

8条回答
jianxiangxiong
2020-12-15 17:10

@Configuration

@ConditionalOnWebApplication(

    type = Type.SERVLET

)

public class ServletEndpointManagementContextConfiguration {

    public ServletEndpointManagementContextConfiguration() {

    }

 

    @Bean

    public ExposeExcludePropertyEndpointFilter servletExposeExcludePropertyEndpointFilter(WebEndpointProperties properties) {

        Exposure exposure = properties.getExposure();

        return new ExposeExcludePropertyEndpointFilter(ExposableServletEndpoint.class, exposure.getInclude(), exposure.getExclude(), new String[0]);

    }

 

    @Configuration

    @ConditionalOnClass({ResourceConfig.class})

    @ConditionalOnMissingClass({"org.springframework.web.servlet.DispatcherServlet"})

    public class JerseyServletEndpointManagementContextConfiguration {

        public JerseyServletEndpointManagementContextConfiguration() {

        }

 

        @Bean

        public ServletEndpointRegistrar servletEndpointRegistrar(WebEndpointProperties properties, ServletEndpointsSupplier servletEndpointsSupplier) {

            return new ServletEndpointRegistrar(properties.getBasePath(), servletEndpointsSupplier.getEndpoints());

        }

    }

 

    @Configuration

    @ConditionalOnClass({DispatcherServlet.class})

    public class WebMvcServletEndpointManagementContextConfiguration {

        private final ApplicationContext context;

 

        public WebMvcServletEndpointManagementContextConfiguration(ApplicationContext context) {

            this.context = context;

        }

 

        @Bean

        public ServletEndpointRegistrar servletEndpointRegistrar(WebEndpointProperties properties, ServletEndpointsSupplier servletEndpointsSupplier) {

            DispatcherServletPathProvider servletPathProvider = (DispatcherServletPathProvider)this.context.getBean(DispatcherServletPathProvider.class);

            String servletPath = servletPathProvider.getServletPath();

            if (servletPath.equals("/")) {

                servletPath = "";

            }

 

            return new ServletEndpointRegistrar(servletPath + properties.getBasePath(), servletEndpointsSupplier.getEndpoints());

        }

    }

}

自上而下观察整个类的代码,你会发现这些自动装配的套路都是一样的

1、如果当前是Servlet环境则装配这个bean

2、当存在类ResourceConfig以及不存在类DispatcherServlet时装配JerseyServletEndpointManagementContextConfiguration

3、当存在DispatcherServlet类时装配WebMvcServletEndpointManagementContextConfiguration


一周热门 更多>