zoukankan      html  css  js  c++  java
  • Spring-2-官网学习

    spring生命周期回调

    结合生命周期机制(官网提供

      1、实现InitializingBean接口重写void afterPropertiesSet() throws Exception;方法

        使用场景:再bean构造方法不方便处理场景下可以使用以上方式进行处理。

      2、自定义init方法(xml)

        <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

        

    public class ExampleBean {
    
        public void init() {
            // do some initialization work
        }
    }
    

      

      3、注解方式@PostConstruct

    public class ExampleBean {
       @PostConstruct 
        public void init() {
            // 此方法名随便定义,最好使用此种方式,非侵入式
        }
    }
    

      

    销毁回调就不在重复记录,官网很明确。

     从Spring 2.5开始,您有三个控制bean生命周期行为的选项:

    includeFiltersexcludeFilters

      使用场景:对某一bean进行排除过滤或者添加过滤使用

      

    @Configuration
    @ComponentScan(basePackages = "org.example",
            includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
            excludeFilters = @Filter(Repository.class))
    public class AppConfig {
        ...
    }
    

      

      

    @Primary注释使用

      使用场景,当两个数据源或者bean为了告诉系统那个是主要的则使用@primary

      由于按类型自动装配可能会导致多个候选人,因此通常需要对选择过程进行更多控制。实现这一目标的一种方法是使用Spring的@Primary注释。@Primary表示当多个bean可以自动装配到单值依赖项时,应该优先选择特定的bean。如果候选者中只存在一个主bean,则它将成为自动装配的值

      

    @Configuration
    public class MovieConfiguration {
    
        @Bean
        @Primary
        public MovieCatalog firstMovieCatalog() { ... }
    
        @Bean
        public MovieCatalog secondMovieCatalog() { ... }
    
        // ...
    }
    

      

    @Primary注释使用

       @Primary当可以确定一个主要候选者时,是通过具有多个实例的类型使用自动装配的有效方式。当您需要更多控制选择过程时,可以使用Spring的@Qualifier注释。您可以将限定符值与特定参数相关联,缩小类型匹配集,以便为每个参数选择特定的bean。在最简单的情况下,这可以是一个简单的描述性值

    生成候选组件索引

      使用场景,大型应用启动性能较慢的情况

      虽然类路径扫描速度非常快,但可以通过在编译时创建候选的静态列表来提高大型应用程序的启动性能。在此模式下,所有作为组件扫描目标的模块都必须使用此机制。

      要生成索引,请为包含组件扫描指令目标的组件的每个模块添加其他依赖项。以下示例显示了如何使用Maven执行此操作:

      

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-indexer</artifactId>
            <version>5.1.8.RELEASE</version>
            <optional>true</optional>
        </dependency>
    </dependencies>
    

      

      对于Gradle 4.5及更早版本,应在compileOnly 配置中声明依赖项,如以下示例所示

    dependencies {
        compileOnly "org.springframework:spring-context-indexer:5.1.8.RELEASE"
    }
    

      

      使用Gradle 4.6及更高版本时,应在annotationProcessor 配置中声明依赖项,如以下示例所示:

    dependencies {
        annotationProcessor "org.springframework:spring-context-indexer:5.1.8.RELEASE"
    }
    

      

  • 相关阅读:
    bzoj2161 布娃娃
    bzoj2161 布娃娃
    Tyvj1054
    Tyvj1054
    Tyvj1053
    Tyvj1053
    hdu3265 Poster(扫描线)
    hdu3265 Poster(扫描线)
    hdu3265(好题翻译)
    hdu3265(好题翻译)
  • 原文地址:https://www.cnblogs.com/gnwzj/p/11082014.html
Copyright © 2011-2022 走看看