2021-11(java-springboot学习笔记二)

目录

自动配置一

自动配置二

容器功能

1、@Configuration和@Bean的基本使用与作用

主启动类的分析

web场景

1.静态资源规则

2.静态资源配置原理


自动配置一

1、父依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

它的父亲

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.6.0</version>
  </parent>

子项目都继承了父项目的依赖,所以需要的时候只需要引入即可

当我们需要指定依赖的版本号时,只需要在子项目文件中引入<properties>,指定版本号即可

 <properties>
     <mysql.version>5.1.43</mysql.version>
 </properties>

<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
 </dependency>

在使用springboot的时候会发现 spring-boot-starter-* 这样的引入。*代表一组依赖。例如引入web

则会把web需要的依赖全部引入

也有 *-spring-boot-starter  这是第三方提供的场景启动器

自动配置二

自动装配tomcat

  1. 引入tomcat
  2. spring boot自动配置
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.6.0</version>
      <scope>compile</scope>
    </dependency>

容器功能

1、@Configuration和@Bean的基本使用与作用

        @component创建的是简单对象,bean创建的是复杂对象

public class Pet {
    private String name;
    private Integer age;
    ...
    // getter and setter
    // toString()
}

在spring时,我们要注入容器,也可以使用@Component

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 向容器里注册一个组件Pet,id为pet -->
    <bean id="pet" class="com.laizhenghua.boot_helloworld.bean.Pet">
        <property name="name" value="tom"/>
        <property name="age" value="20"/>
    </bean>
</beans>

但是在spring boot中

@Configuration // 标准这个类是一个配置配置类,这个类等同于配置文件
public class MyConfig {
	// @Bean("tom") 自定义组件id  组定义名字
    @Bean // 给容器中添加组件,方法名作为组件的id,返回值类型就是组件类型,方法返回值就是组件中的实例!
    public Pet pet() {
        Pet pet = new Pet();
        pet.setName("tom");
        pet.setAge(20);
        return pet;
    }
    /*
    <bean id="pet" class="com.laizhenghua.boot_helloworld.bean.Pet">
        <property name="name" value="tom"/>
        <property name="age" value="20"/>
    </bean>
     */
}

注意:容器中注册默认的时单例模式

@Configuration(proxyBeanMethods = true)

true:为代理模式

false:单例模式:会直接new

组件依赖问题:

  • 一个人类,一个动物类。人养动物。通过人类set方法动物类和本身动物类为同一个

@Conditional:满足一定条件才进行组件注入

@ConditionalOnBean:只有容器中有,他才有。

例如:使用在tom1上写@ConditionalOnBean( name = "tom")

tom容器中没有,tom1也没有

配置绑定,类里面的信息和配置文件绑定

@ConfigurationProperties(prefix="dog")

注意:只有在容器中才能这个使用  @Component

        :开启配置绑定功能 @EnableConfigurationProperties(Dog.class)  

主启动类的分析


//@SpringBootApplication 来标注一个主程序类
//说明这是一个Spring Boot应用
@SpringBootApplication
public class SpringbootApplication {

   public static void main(String[] args) {
     //以为是启动了一个方法,没想到启动了一个服务
      SpringApplication.run(SpringbootApplication.class, args);
   }

}

@SpringBootApplication

作用:标注在某个类上,说明是springboot主配置类,springboot就应该运行这个类的main方法来启动springboot应用。

进入这个注解,上面还有其他注解!


@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    // ......
}

@ComponentScan

这个注解很重要,它对应xml配置中的元素。

作用:自动扫描并加载符合条件的组件或者bean,将这个bean定义加载到ioc容器中

@SpringBootConfiguration

作用:springboot的配置类,标注在某个类上,表示这是一个springboot的配置类;

点进这个类

这里的 @Configuration,说明这是一个配置类 ,配置类就是对应Spring的xml 配置文件;

里面的 @Component 这就说明,启动类本身也是Spring中的一个组件而已,负责启动应用!

@EnableAutoConfiguration

告诉springboot开启自动配置功能

点进去

@AutoConfigurationPackage:自动配置包


@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}

@import:spring底层注解,给容器导入一个组件

Registrar.class 作用:将主启动类的所在包及包下面所有子包里面的所有组件扫描到Spring容器 

web场景

1.静态资源规则

静态资源可以存放在:

  • 资源包下的META-INF——>resources——>静态资源
  • public——>静态资源
  • resources——>静态资源
  • static——>静态资源

原理:静态映射/**

请求进来,先去controller看看能不能处理,不能的话去找静态资源。都没有就报404

静态资源访问前缀:

spring:
  mvc:
    static-path-pattern: /res/**

首页:在能访问的静态资源下直接写index.html

注意:当配置访问前缀时:首页和图标都会失效

2.静态资源配置原理

spring boot启动默认加载,×××AutoConfiguration类(自动配置类)

springmvc功能的自动配置类WebMvcAutoConfiguration() 

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
   
   

扩展:一个配置类只有一个有参构造类

        public WebMvcAutoConfigurationAdapter(WebProperties webProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
            this.resourceProperties = webProperties.getResources();
            this.mvcProperties = mvcProperties;
            this.beanFactory = beanFactory;
            this.messageConvertersProvider = messageConvertersProvider;
            this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
            this.dispatcherServletPath = dispatcherServletPath;
            this.servletRegistrations = servletRegistrations;
            this.mvcProperties.checkConfiguration();
        }

静态资源页的规则:

        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
                this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
                    registration.addResourceLocations(this.resourceProperties.getStaticLocations());
                    if (this.servletContext != null) {
                        ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                        registration.addResourceLocations(new Resource[]{resource});
                    }

                });
            }
        }

猜你喜欢

转载自blog.csdn.net/qq_45688193/article/details/121528465