SpringBoot⾃动装配原理
根据之前的学习,在搭建springboot项⽬时,我们可以简化很多配置。那springboot是如何做到的呢?
⾸先我们来看JAVA WEB的启动过程
web项⽬需要部署容器(tomcat\weblogic等),容器会⾸先加载web项⽬中的 l⽂件。
项⽬的启动顺序⾸先是context-param,接着是listener,在接下来是filter,最后才是servlet。
知识点
SpringMVC
springmvc的启动过程也是基于上述过程。
tomcat容器 会将读取到<context-param>转化为键值对,并交给ServletContext(上下⽂) ,供整个WEB项⽬使⽤
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
在执⾏玩上下⽂加载后会建⽴监听,ServletContextListener作为监听类的根接⼝contextInitialized,contextDestroyed两个⽅法。
<!---->
<listener>
<listener-class>org.t.ContextLoaderListener</listener-class>
</listener>
⽽ ContextLoaderListener 重写了 contextInitialized ⽅法
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext());
}
初始化Web应⽤上下⽂,initWebApplicationContext中调⽤configureAndRefreshWebApplicationContext对IoC容器的配置和刷新操作。
该⽅法主要⽤于创建并初始化contextConfigLocation类配置的xml⽂件中的Bean,因此,如果我们在配置Bean时出错,在Web应⽤启动时就会抛出异常,⽽不是等到运⾏时才抛出异常。
filter初始化
servlet初始化
常⽤DispatcherServlet类,DispatcherServlet类间接⽗类实现了Servlet接⼝,创建⼀个IOC⼦容器,并加载<servlet>标签的<init-param>配置的xml⽂件并加载相关Bean。
SpringBoot的启动过程
我们来看springboot的启动类
@SpringBootApplication
@Slf4j
public class Application
{
public static void main(String[] args)
{
log.info("=================开始成功=================");
SpringApplication.run(Application.class, args);
log.info("=================启动成功=================");
}
@SpringBootApplication注解是springboot启动的开始,我们来看看
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
Class<?>[] exclude() default {};
String[] excludeName() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
}
@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 是其中最重要的三个注解
@SpringBootConfiguration 注解
@SpringBootConfiguration其实就是@Configuration,熟悉spring的都知道,@Configuration 是⼀个类级注释,指⽰对象是⼀个bean定义的源。@Configuration 类通过 @bean 注解的公共⽅法声明bean。减少xml配置。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
例如:
<beans>
<bean id="orderService" class="com.acme.OrderService"/>
<constructor-arg ref="orderRepository"/>
</bean>
spring ioc注解<bean id="orderRepository" class="com.acme.OrderRepository"/>
<constructor-arg ref="dataSource"/>
</bean>
</beans>
使⽤@Configuration
@Configuration
public class ApplicationConfig {
public @Bean OrderService orderService() {
return new OrderService(orderRepository());
}
public @Bean OrderRepository orderRepository() {
return new OrderRepository(dataSource());
}
public @Bean DataSource dataSource() {
}
}
@ComponentScan告诉Spring 哪个packages 的⽤注解标识的类 会被spring⾃动扫描并且装⼊bean容器。
@EnableAutoConfiguration
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "ableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
@EnableAutoConfiguration让Spring Boot根据类路径的jar包依赖为当前项⽬进⾏⾃动化配置。
例如,添加了spring-boot-starter-web依赖,会⾃动添加Tomcat和Spring MVC的依赖,那么Spring Boot会对Tomcat和Spring MVC 进⾏⾃动配置。
⼜如,添加了spring-boot-starter-data-jpa依赖,Spring Boot会⾃动进⾏JPA相关的配置。
进⼊@EnableAutoConfiguration
查看getCandidateConfigurations⽅法
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
"No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
SpringFactoriesLoader.loadFactoryNames加载META-INF/spring.factories⽂件中jar⽂件例如spring-boot-1.4.2.RELEASE.jar 中的META-INF/spring.factories
org.v.PropertySourceLoader=\
org.v.PropertiesPropertySourceLoader,\
org.v.YamlPropertySourceLoader
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.t.event.EventPublishingRunListener
# Application Context Initializers
t.ApplicationContextInitializer=\
org.t.ConfigurationWarningsApplicationContextInitializer,\ org.t.ContextIdApplicationContextInitializer,\
org.t.config.DelegatingApplicationContextInitializer,\
org.t.web.ServerPortInfoApplicationContextInitializer
# Application Listeners
t.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.t.FileEncodingApplicationListener,\
org.t.config.AnsiOutputApplicationListener,\
org.t.config.ConfigFileApplicationListener,\
org.t.config.DelegatingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener,\
org.springframework.boot.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.logging.LoggingApplicationListener
# Environment Post Processors
org.v.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.v.SpringApplicationJsonEnvironmentPostProcessor
# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer
# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter
我们在springmvc中使⽤redis
需要配置⼀些bean,如:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论