SpringBoot框架:永恒的hello world,@SpringBootApplication的源代码简单查看

永恒的hello world

浏览器发送hello请求,服务器接受请求并处理,响应Hello World字符串;

  1. 先创建一个maven工程
  2. 导入springboot相关的依赖
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
  1. 编写主程序,启动spring boot应用
package jane;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author jane
 * @create 2020-07-31 0:59
 */

/**
 * @SpringBootApplication用来标注一个主程序类,说明这是spring boot应用
 */
@SpringBootApplication
public class Helloworld
{
    public static void main(String[] args)
    {
        SpringApplication.run(Helloworld.class, args);
    }

}

  1. 编写相关的Controller
package jane;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * @author jane
 * @create 2020-07-31 7:53
 */
@Controller
public class HelloController
{
    @ResponseBody
    @RequestMapping("/hello")
    public String hello()
    {
        return "hello world";
    }
}
  1. 运行主程序测试
  2. 简化部署
    <!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

将这个应用打成jar包,直接使用java -jar jar文件名称 的命令进行执行

hello world的探索

POM文件

  1. 父项目
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

它的再一次父项目

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-dependencies</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath>../../spring-boot-dependencies</relativePath>
	</parent>
这个就是用来真正管理spring boot应用里面的所有依赖的版本
里面的properties标签写了很多的版本号
相当于Spring Boot的版本仲裁中心;
以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖自然需要声明版本号) 
  1. 启动器
<dependency>     
	<groupId>org.springframework.boot</groupId>     			
	<artifactId>spring‐boot‐starter‐web</artifactId> 
</dependency>

spring-boot-starter-web:
spring-boot-starter:spring-boot场景启动器;帮我们导入了web模块正常运行所依赖的组件;

Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter 相关场景的所有依赖都会导入进来。要用什么功能就导入什么场景的启动器
具体的场景启动器查看官方文档进行了解,官方文档

主程序类

package jane;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Helloworld
{
    public static void main(String[] args)
    {
        SpringApplication.run(Helloworld.class, args);
    }
}

@SpringBootApplication

这是spring boot应用标注某个类上说明这个类是spring boot的主配置类,spring boot就应该运行这个类的main方法来启动spring boot应用
这个注解内容是

@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

Spring Boot的配置类;
标注在某个类上,表示这是一个Spring Boot的配置类;
@SpringBootConfiguration里面的注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

其中的@Configuration:是配置类上来标志这个注解
这里的配置类相当于学习spring的配置文件,配置类也是容器中的一个组件,@Component
@Configuration里面的内容

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    String value() default "";
}
@EnableAutoConfiguration

开启自动配置功能;
以前我们需要配置的东西,Spring Boot帮我们自动配置;
@EnableAutoConfiguration告诉SpringBoot开启自 动配置功能;这样自动配置才能生效;
里面的内容是:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

里面的
@AutoConfigurationPackage:自动配置包
里面的内容

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}

@Import(AutoConfigurationPackages.Registrar.class):
Spring的底层注解@Import,给容器中导入一个组件;导入的组件由 AutoConfigurationPackages.Registrar.class;决定,
AutoConfigurationPackages.Registrar.class里面的内容是

    static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
        Registrar() {
        }

        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
            AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
        }

        public Set<Object> determineImports(AnnotationMetadata metadata) {
            return Collections.singleton(new AutoConfigurationPackages.PackageImport(metadata));
        }
    }

由registerBeanDefinitions方法的(new AutoConfigurationPackages.PackageImport(metadata)).getPackageName()可知道就是得到主配置类的包名
然后registerBeanDefinitions这个方法是注册bean定义信息,就是将主配置类所在包及以下的组件扫描进容器

所以@AutoConfigurationPackage的作用就是:
将主配置类(@SpringBootApplication标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器;

@EnableAutoConfiguration还有一个
@Import({EnableAutoConfigurationImportSelector.class})
首先@import是给容器导入组件
EnableAutoConfigurationImportSelector:导入哪些组件的选择器
将所有需要导入的组件以全类名的方式返回,这些组件会被加载到容器中,最终的效果就是会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景需要的所有组件, 并配置好这些组件;
有了自动配置类,免去了我们手动编写配置注入功能组件等的工作.

接下来我们看下EnableAutoConfigurationImportSelector原码了解一下它到底干了什么

public class EnableAutoConfigurationImportSelector extends AutoConfigurationImportSelector {
    public EnableAutoConfigurationImportSelector() {
    }

    protected boolean isEnabled(AnnotationMetadata metadata) {
        return this.getClass().equals(EnableAutoConfigurationImportSelector.class) ? (Boolean)this.getEnvironment().getProperty("spring.boot.enableautoconfiguration", Boolean.class, true) : true;
    }
}

这里的它自己没什么方法,找它的父类AutoConfigurationImportSelector 查看
在这里插入图片描述
在这里插入图片描述
导入了这么多的自动配置类,那么这些自动配置类到底是在哪里来的呢?
让我们继续下集更加精彩

 List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);

进入getCandidateConfigurations

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
    }

进入loadFactoryNames

    public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();

        try {
            Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
            ArrayList result = new ArrayList();

            while(urls.hasMoreElements()) {
                URL url = (URL)urls.nextElement();
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                String factoryClassNames = properties.getProperty(factoryClassName);
                result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
            }

            return result;
        } catch (IOException var8) {
            throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() + "] factories from location [" + "META-INF/spring.factories" + "]", var8);
        }
    }

META-INF/spring.factories中的内容
在这里插入图片描述

Spring Boot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将 这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作;以前我们需要自己配置的东 西,自动配置类都帮我们;
J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-1.5.9.RELEASE.jar;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReflectMirroring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值