SpringBoot自动装配

347 阅读5分钟

依赖的管理

对于所有的依赖我们需要在父项目中设置版本号等都设置好了,在子项目中就不需要再配置版本

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
</parent>
他的父项目
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4.RELEASE</version>
  </parent>

但是如果想要使用非SpringBoot官方引入的jar的话就需要写版本号

starter场景启动器

  1. 很多spring-boot-starter-就某种场景
  2. 只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
  3. SpringBoot所有支持的场景
  4. -spring-boot-starter: 第三方为我们提供的简化开发的场景启动器

自动配置

自动配置好Tomcat ,SpringMVC , SpringMVC中的常见组件 ,配置好了web的常见功能 。

下面是我们打印一个请求时查看SpringBoot所启用的组件

组件:  org.springframework.context.annotation.internalConfigurationAnnotationProcessor
组件:  org.springframework.context.annotation.internalAutowiredAnnotationProcessor
组件:  org.springframework.context.annotation.internalCommonAnnotationProcessor
组件:  org.springframework.context.event.internalEventListenerProcessor
组件:  org.springframework.context.event.internalEventListenerFactory
组件:  mainApplication
组件:  org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
组件:  helloController
组件:  org.springframework.boot.autoconfigure.AutoConfigurationPackages
组件:  org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
组件:  propertySourcesPlaceholderConfigurer
组件:  org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
组件:  websocketServletWebServerCustomizer
组件:  org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
组件:  org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
组件:  tomcatServletWebServerFactory
组件:  org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
组件:  servletWebServerFactoryCustomizer
组件:  tomcatServletWebServerFactoryCustomizer
组件:  org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
组件:  org.springframework.boot.context.internalConfigurationPropertiesBinderFactory
组件:  org.springframework.boot.context.internalConfigurationPropertiesBinder
组件:  org.springframework.boot.context.properties.BoundConfigurationProperties
组件:  org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
组件:  server-org.springframework.boot.autoconfigure.web.ServerProperties
组件:  webServerFactoryCustomizerBeanPostProcessor
组件:  errorPageRegistrarBeanPostProcessor
组件:  org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
组件:  dispatcherServlet
组件:  spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
组件:  org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
组件:  dispatcherServletRegistration
组件:  org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
组件:  org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
组件:  taskExecutorBuilder
组件:  applicationTaskExecutor
组件:  spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties
组件:  org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
组件:  error
组件:  beanNameViewResolver
组件:  org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
组件:  conventionErrorViewResolver
组件:  org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
组件:  errorAttributes
组件:  basicErrorController
组件:  errorPageCustomizer
组件:  preserveErrorControllerTargetClassPostProcessor
组件:  spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
组件:  org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
组件:  requestMappingHandlerAdapter
组件:  requestMappingHandlerMapping
组件:  welcomePageHandlerMapping
组件:  mvcConversionService
组件:  mvcValidator
组件:  mvcContentNegotiationManager
组件:  mvcPathMatcher
组件:  mvcUrlPathHelper
组件:  viewControllerHandlerMapping
组件:  beanNameHandlerMapping
组件:  routerFunctionMapping
组件:  resourceHandlerMapping
组件:  mvcResourceUrlProvider
组件:  defaultServletHandlerMapping
组件:  handlerFunctionAdapter
组件:  mvcUriComponentsContributor
组件:  httpRequestHandlerAdapter
组件:  simpleControllerHandlerAdapter
组件:  handlerExceptionResolver
组件:  mvcViewResolver
组件:  mvcHandlerMappingIntrospector
组件:  org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
组件:  defaultViewResolver
组件:  viewResolver
组件:  requestContextFilter
组件:  org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
组件:  formContentFilter
组件:  org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
组件:  mbeanExporter
组件:  objectNamingStrategy
组件:  mbeanServer
组件:  org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
组件:  springApplicationAdminRegistrar
组件:  org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$ClassProxyingConfiguration
组件:  org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
组件:  org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration
组件:  applicationAvailability
组件:  org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
组件:  org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration
组件:  lifecycleProcessor
组件:  spring.lifecycle-org.springframework.boot.autoconfigure.context.LifecycleProperties
组件:  org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
组件:  standardJacksonObjectMapperBuilderCustomizer
组件:  spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
组件:  org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
组件:  jacksonObjectMapperBuilder
组件:  org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
组件:  parameterNamesModule
组件:  org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
组件:  jacksonObjectMapper
组件:  org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
组件:  jsonComponentModule
组件:  org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
组件:  stringHttpMessageConverter
组件:  org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
组件:  mappingJackson2HttpMessageConverter
组件:  org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
组件:  org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
组件:  messageConverters
组件:  org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
组件:  spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
组件:  org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration
组件:  taskSchedulerBuilder
组件:  spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties
组件:  org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
组件:  restTemplateBuilder
组件:  org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
组件:  tomcatWebServerFactoryCustomizer
组件:  org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
组件:  org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
组件:  characterEncodingFilter
组件:  localeCharsetMappingsCustomizer
组件:  org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
组件:  multipartConfigElement
组件:  multipartResolver
组件:  spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
组件:  org.springframework.aop.config.internalAutoProxyCreator
2023-01-14 08:40:52.385  INFO 8564 --- [nio-8888-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-01-14 08:40:52.385  INFO 8564 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-01-14 08:40:52.388  INFO 8564 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms

使用* @ComponentScan("包名")可以改变扫描路径

在之前我们使用的@SpringBootApplication ,他只能扫描自己所在包里面的所有的组件
使用@ComponentScan("包名") 和下面的另外两个就可以代替@SpringBootAplication
    
// @SpringBootConfiguration             }
// @EnableAutoConfiguration             } == 》 @SpringBootApplication
// @ComponentScan("com.atguigu.boot")   }

各种配置拥有默认值

  • 默认配置最终都是映射到某个类上,如:MultipartProperties
  • 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象

按需加载所有自动配置项

    • 非常多的starter
    • 引入了哪些场景这个场景的自动配置才会开启
    • SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面

a

容器管理

原生的spring添加组件的方法:

创建一个spring.xml的类,然后配置组件的信息,注册组件

img

SpringBoot中添加组件的方法:

  1. 创建一个类,将这个类设置为配置类
@Configuration      //用来告诉SpringBoot 这是一个配置文件类  
//@Configuration(proxyBeanMethods = false) //设置多实例对象
public class MyConfig {
    
    @Bean
    public User user1(){
        /*给容器中添加组件,一方法名作为组件的id , 返回类型就是组件类型 , 值就是组件中的内容实例*/
        return new User("zhansan",12);
    }
    //等同于下面的
    /**
    <bean id="user1" class="com.ray.bean.User">
        <property name="name" value="da"/>
        <property name="age" value="11"/>
    </bean>
    */   
    @Bean("tom")  // 也可以直接在bean中设置组件的id
    public Pet tomcatPet(){
        return new tomcat("tom" , 11);
    }
    
}
  1. 给方法名设置@Bean注解,将方法名当做组件的id ,返回类型就是组件类型 ,返回值就是组件在容器中的实例(对象)
  2. @Configuration(proxyBeanMethods = false) // 中默认的是true 。
   值为true 那么无论我们调用多少次组件,他返回的都是单例的。【每次调用都是获取容器中唯一的】
      值为false :【 那么我们每个@Bean方法被调用多少次返回多少个新的组件】

其他组件

@Bean、@Component、@Controller、@Service、@Repository(数据库组件)

@ComponentScan(指定包扫描的)、@Import(放在任何一个组件上面都行)

@Import({ XXX.class, AAA.class ....} ) 组件

作用:给容器导入组件,他是一个数组类型的

可以自动的给容器中创建调用这其中组件的无参构造器 ,从而创建出指定类型的对象 [默认组件的名字就是全类名]

条件装配组件@Conditional (如果条件满足或者说如果条件不满足才执行XXX组件)

继承类:@ConditionalOnBean(name = "tom")

//条件组件,就是当我们的类中有名为tom的时候,我们类中的XXX组件才会被执行,才会生效

@ConditionalOnBean(name = "tom")    
@Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public User user01(){
    User zhangsan = new User("zhangsan", 18);
    //user组件依赖了Pet组件
    zhangsan.setPet(tomcatPet());
    return zhangsan;
}
​
@Bean("tom22")
public Pet tomcatPet(){
    return new Pet("tomcat");
}

如果将条件组件标记在类上,那么就是除非类中有tom组件,配置配种的其他组件才会被执行

@Configuration      //用来告诉SpringBoot 这是一个配置文件类  
//@Configuration(proxyBeanMethods = false) //设置多实例对象
@Conditional(name = "tom")
public class MyConfig {
​
}
    

其他条件装配注解

img

配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }
  1. @* ConfigurationProperties* @Component只有在容器中的组件,才会拥有SpringBoot提供的强大功能 @ConfigurationProperties(prefix = "mycar") //将类放入容器中(@Compnent),然后与javaBean (mycar)与配置绑定img

img

//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
  1. 开启属性配置功能

@EnableConfigurationProperties (在配置类中) + @ConfigurationProperties(在javaBean类中) = 就是开启属性配置,然后将配置与javaBean绑定

@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}
​
//在Car类中就不需要使用@Component注解@ConfigurationProperties(prefix = "mycar")
public class Car {

参考说明: 尚硅谷雷神SpringBoot