springboot 注解
@SpringBootApplication
包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让spring Boot扫描到Configuration类并把它加入到程序上下文。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}
上面的元注解我们在这里不在做解释,相信大家在开发当中肯定知道,我们要来说@SpringBootConfiguration @EnableAutoConfiguration 这两个注解,
到这里我们知道 SpringBootApplication注解里除了元注解,我们可以看到又是@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan的组合注解,
官网上也有详细说明,那我们现在把目光投向这三个注解。
@SpringBootConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
我们可以看到这个注解除了元注解以外,就只有一个@Configuration,那也就是说这个注解相当于@Configuration,所以这两个注解作用是一样的,那他是干嘛的呢,
相信很多人都知道,它是让我们能够去注册一些额外的Bean,并且导入一些额外的配置。
那@Configuration还有一个作用就是把该类变成一个配置类,不需要额外的XML进行配置。所以@SpringBootConfiguration就相当于@Configuration。
@EnableAutoConfiguration,这个注解官网说是 让Spring自动去进行一些配置
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
@AutoConfigurationPackage,他是说:让包中的类以及子包中的类能够被自动扫描到spring容器中。
@Import(EnableAutoConfigurationImportSelector.class)这个是核心,之前我们说自动配置,那他到底帮我们配置了什么,怎么配置的?
就和@Import(EnableAutoConfigurationImportSelector.class)息息相关,程序中默认使用的类就自动帮我们找到。我们来看EnableAutoConfigurationImportSelector.class
public class EnableAutoConfigurationImportSelector
extends AutoConfigurationImportSelector {
@Override
protected boolean isEnabled(AnnotationMetadata metadata) {
if (getClass().equals(EnableAutoConfigurationImportSelector.class)) {
return getEnvironment().getProperty(
EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class,
true);
}
return true;
}
}
可以看到他继承了AutoConfigurationImportSelector我们继续来看AutoConfigurationImportSelector,这个类有一个方法
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
try {
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
configurations = removeDuplicates(configurations);
configurations = sort(configurations, autoConfigurationMetadata);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return configurations.toArray(new String[configurations.size()]);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
这个类会帮你扫描那些类自动去添加到程序当中。我们可以看到getCandidateConfigurations()这个方法,
他的作用就是引入系统已经加载好的一些类,到底是那些类呢,我们点进去看一下
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
Assert.notEmpty(configurations,
"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;
}
这个类回去寻找的一个目录为META-INF/spring.factories,也就是说他帮你加载让你去使用也就是在这个META-INF/spring.factories目录装配的,他在哪里?

我们点进spring.factories来看

我们可以发现帮我们配置了很多类的全路径,比如你想整合activemq,或者说Servlet

可以看到他都已经帮我们引入了进来,我看随便拿几个来看
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
比如我们经常用的security,可以看到已经帮你配置好,所以我们的EnableAutoConfiguration主要作用就是让你自动去配置,
但并不是所有都是创建好的,是根据你程序去进行决定。 那我们继续来看
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM,
classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM,
classes = AutoConfigurationExcludeFilter.class) })
这个注解大家应该都不陌生,扫描包,放入spring容器,那他在springboot当中做了什么策略呢?
我们可以点跟烟去思考,帮我们做了一个排除策略,他在这里结合SpringBootConfiguration去使用,为什么是排除,因为不可能一上来全部加载,因为内存有限。
那么我们来总结下@SpringbootApplication:就是说,他已经把很多东西准备好,具体是否使用取决于我们的程序或者说配置,那我们到底用不用?
那我们继续来看一行代码
public static void main(String[] args)
{
SpringApplication.run(StartEurekaApplication.class, args);
}
那们来看下在执行run方法到底有没有用到哪些自动配置的东西,比如说内置的Tomcat,那我们来找找内置Tomcat,我们点进run
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
return new SpringApplication(sources).run(args);
}
然后他调用又一个run方法,我们点进来看
public ConfigurableApplicationContext run(String... args) {
//计时器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
//监听器
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
//准备上下文
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
//预刷新context
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//刷新context
refreshContext(context);
//刷新之后的context
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
那我们关注的就是 refreshContext(context); 刷新context,我们点进来看
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
我们继续点进refresh(context);
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
他会调用 ((AbstractApplicationContext) applicationContext).refresh();方法,我们点进来看
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.
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的bean的加载过程我在,解析springIOC加载过程的时候介绍过这里面的方法,如果你看过Spring源码的话 ,
应该知道这些方法都是做什么的。现在我们不关心其他的,我们来看一个方法叫做 onRefresh();方法
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
他在这里并没有实现,但是我们找他的其他实现,我们来找

我们既然要找Tomcat那就肯定跟web有关,我们可以看到有个ServletWebServerApplicationContext
@Override
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
我们可以看到有一个createWebServer();方法他是创建web容器的,而Tomcat不就是web容器,那他是怎么创建的呢,我们继续看
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context",
ex);
}
}
initPropertySources();
}
factory.getWebServer(getSelfInitializer());他是通过工厂的方式创建的
public interface ServletWebServerFactory {
WebServer getWebServer(ServletContextInitializer... initializers);
}
我们看到还有Jetty,那我们来看TomcatServletWebServerFactory
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory
: createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
那这块代码,就是我们要寻找的内置Tomcat,在这个过程当中,我们可以看到创建Tomcat的一个流程。因为run方法里面加载的东西很多,所以今天就浅谈到这里。
如果不明白的话, 我们在用另一种方式来理解下,大家要应该都知道stater举点例子
@Controller ,@RestController
用于标注是控制层组件,需要返回页面时请用@Controller而不是@RestController;
@Controller:用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),
一般这个注解在类中,通常方法需要配合注解@RequestMapping。示例代码:
@Controller
@RequestMapping(“/demoInfo”)
publicclass DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
//会使用hello.html或者hello.ftl模板进行渲染显示.
return"/hello";
}
}
@RestController:用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集。示例代码:
package com.kfit.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
publicclass DemoController2 {
@RequestMapping("/test")
public String test(){
return"ok";
}
}
@RequestMapping ,@GetMapping、@PostMapping等
@RequestMapping 提供路由信息,负责URL到Controller中的具体函数的映射。
该注解有六个属性:
params:指定request中必须包含某些参数值是,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
value:指定请求的实际地址,指定的地址可以是URI Template 模式
method:指定请求的method类型, GET、POST、PUT、DELETE等
consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html;
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。
@GetMapping、@PostMapping等:
相当于@RequestMapping(value=”/”,method=RequestMethod.Get\Post\Put\Delete等) 。是个组合注解;
@ComponentScan
组件扫描。个人理解相当于,如果扫描到有@Component @Controller @Service等这些注解的类,则把这些类注册为bean*;
@Service,@Repository,@Component
@Repository:用于标注数据访问组件,即DAO组件;使用@Repository注解可以确保DAO或者repositories提供异常转译,
这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。
@Service:用于标注业务层组件;
@Component:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注;
@AutoWired,@Qualifier
byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作;
当加上(required=false)时,就算找不到bean也不报错;
@Qualifier:当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。
@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
参考:
你应该知道的 @ConfigurationProperties 注解的使用姿势,这一篇就够了
SpringBoot 中使用 @Valid 注解 + Exception 全局处理器优雅处理参数验证
Spring Boot 中 @EnableXXX 注解的驱动到底是什么逻辑?
SpringBoot + Redis + 注解 + 拦截器来实现接口幂等性校验
SpringBoot + Redis + 注解 + 拦截器来实现接口幂等性校验
254.Security注解:@PreAuthorize,@PostAuthorize, @Secured, EL实现方法安全
超级全面的 SpringBoot 注解介绍,每一个用途都应该清晰
SpringBoot:切面AOP实现权限校验:实例演示与注解全解
Spring Boot 整合Spring Security示例实现前后分离权限注解+JWT登录认证
接近8000字的Spring/SpringBoot常用注解总结!安排!
面试:你简历上写深入理解SpringBoot,给我讲讲它的关键注解?
Spring Boot 解决 json 日期格式化疑难问题,基于注解实现全局日期格式化
Spring Boot从入门到精通(三)常用注解含义及用法分析总结
经典面试:Spring Boot中的条件注解底层是如何实现的?


浙公网安备 33010602011771号