current position:Home>Spring framework learning - supplement to path scanning and management components such as spring IOC

Spring framework learning - supplement to path scanning and management components such as spring IOC

2022-01-26 22:36:06 TyuIn

Follow up with a blog :https://blog.csdn.net/qq_43605444/article/details/121977933?spm=1001.2014.3001.5502

11.6 Name automatically detected components

When a component is automatically detected as part of the scanning process , its bean The name is known by the scanner BeanNameGenerator Strategy generation . By default , Any that contains a name value Spring Constructive annotation (@Component、@Repository、@Service and @Controller) This provides the name to the corresponding bean Definition .

If such annotations do not contain name values or any other detected components ( For example, components found by custom filters ), By default bean The name generator returns an unqualified class name that is not capitalized . for example , If the following component classes are detected , The name will be myMovieLister and movieFinderImpl:

@Service("myMovieLister")
public class SimpleMovieLister {
    
    // ...
}
@Repository
public class MovieFinderImpl implements MovieFinder {
    
    // ...
}

If you don't want to rely on the default bean Naming strategy , You can provide custom bean Naming strategy . First , Realization BeanNameGenerator Interface , And make sure to include a default parameterless constructor . then , Provide a fully qualified class name when configuring the scanner , For example, the following example comments and bean The definition shows .

If multiple automatically detected components have the same unqualified class name ( namely , Classes with the same name but residing in different packages ) And encountered a naming conflict , You may need to configure a BeanNameGenerator, The BeanNameGenerator The default is the fully qualified class name of the class Generated bean name . from Spring Framework 5.2.3 Start , be located org.springframework.context.annotation In bag fullyQualifiedAnnotationBeanNameGenerator Can be used for such purposes .

@Configuration
@ComponentScan(basePackages = "org.example", nameGenerator = MyNameGenerator.class)
public class AppConfig {
    
    // ...
}
<beans>
    <context:component-scan base-package="org.example" name-generator="org.example.MyNameGenerator" />
</beans>

As a general rule , When other components may explicitly reference it , Consider using annotations to specify names . On the other hand , As long as the container is responsible for connecting , Automatically generated names are sufficient .

11.7 Provide scope for automatic detection components

And Spring Managed components are the same , The default and most common range of automatic detection components is singleton . however , Sometimes you need one that can be @Scope Different ranges specified by annotations . You can provide the name of the scope in the annotation , This is shown in the following example :

@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
    
    // ...
}

@Scope Comments are only in specific bean class ( For annotated components ) Or factory methods ( about @Bean Method ) Introspection on . And XML bean Opposite definition , No, bean Define the concept of inheritance , And the inheritance hierarchy at the class level is independent of the purpose of metadata .

Specific to Web The scope of the ( for example Spring In context “ request ” or “ conversation ”) Details of , See request 、 conversation 、 Applications and WebSocket Range . As with the pre built annotations for these scopes , You can also use the Spring Meta annotation method to write your own scope annotation : for example , Use @Scope("prototype") Custom annotations for meta annotations , It is also possible to declare a custom scope proxy pattern .

To provide a custom strategy for scope resolution, rather than relying on annotation based methods , You can achieve ScopeMetadataResolver Interface . Make sure to include the default parameterless constructor . You can then provide a fully qualified class name when configuring the scanner , As noted below and bean The definition example is shown in :

@Configuration
@ComponentScan(basePackages = "org.example", scopeResolver = MyScopeResolver.class)
public class AppConfig {
    
    // ...
}
<beans>
    <context:component-scan base-package="org.example" scope-resolver="org.example.MyScopeResolver"/>
</beans>

When using some non single scopes , You may need to generate a proxy for the scope object . Reasoning in Scoped Beans Described as dependencies in . So , Can be in component-scan Use on element scoped-proxy attribute . Three possible values are :no、interfaces and targetClass. for example , The following configuration will produce a standard JDK A dynamic proxy :

@Configuration
@ComponentScan(basePackages = "org.example", scopedProxy = ScopedProxyMode.INTERFACES)
public class AppConfig {
    
    // ...
}
<beans>
    <context:component-scan base-package="org.example" scoped-proxy="interfaces"/>
</beans>

11.8 Provide qualifier metadata with annotations

@Qualifier Annotations are discussed in using qualifiers to fine tune annotation based automatic assembly . The examples in this section demonstrate the use of @Qualifier Annotations and custom qualifier annotations provide fine-grained control when parsing automatic assembly candidates . Because these examples are based on XML bean Definition , So by using XML in bean Element qualifier or meta sub element , In the candidate bean Provide qualifier metadata on the definition . When relying on classpath scanning to automatically detect components , You can provide type level annotations of candidate classes for qualifier metadata . The following three examples demonstrate this technique :

@Component
@Qualifier("Action")
public class ActionMovieCatalog implements MovieCatalog {
    
    // ...
}
@Component
@Genre("Action")
public class ActionMovieCatalog implements MovieCatalog {
    
    // ...
}
@Component
@Offline
public class CachingMovieCatalog implements MovieCatalog {
    
    // ...
}

As with most annotation based alternatives , Remember that annotation metadata is bound to the class definition itself , and XML The use of allows multiple of the same type bean Provide a variant of its qualifier metadata , Because the metadata is for every - Instance instead of every class .

11.9 Generate index of candidate components

Although classpath scanning is very fast , However, you can improve the startup performance of large applications by creating a static candidate list at compile time . In this mode , All modules targeted for component scanning must use this mechanism .

Your existing @ComponentScan or <context:component-scan/> The instruction must remain unchanged to request the context to scan candidates in some packages . When ApplicationContext When such an index is detected , It will automatically use it instead of scanning the classpath .

To generate an index , Add additional dependencies to each module that contains the component that is the target of the component scan instruction . The following example shows how to use Maven Do this :

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

about Gradle 4.5 And earlier , Should be in compileOnly Declare dependencies in the configuration , This is shown in the following example :

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

about Gradle 4.6 And higher , Should be in annotationProcessor Declare dependencies in the configuration , This is shown in the following example :

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

spring-context-indexer The artifact generates a META-INF/spring.components file , The file is contained in jar In file .

stay IDE When using this mode in ,spring-context-indexer Must be registered as a comment processor , To ensure that the index is up-to-date when the candidate component is updated .

When found on the classpath META-INF/spring.components When you file , Indexing is automatically enabled . If the index is for some libraries ( Or use case ) Some are available but cannot be built for the entire application , You can set spring.index.ignore Back to regular classpath scheduling ( There seems to be no index at all ) It's true , No matter what it is JVM System attribute or pass SpringProperties Mechanism .

Article reference :https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-classpath-scanning

copyright notice
author[TyuIn],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262236015230.html

Random recommended