spring Basic Components and Annotations

spring Basic Components as shown above:

spring configuration file

First use the xml configuration file, then turn to annotations.

//Configuration class ==== configuration file
@Configuration
public class MainConfig {
    //Register a bean in the container with the type of the return value. 
    //Note that the @Bean registered bean, which defaults to the method name, can also be modified by the value of the @Bean annotation
    @Bean
    public Person person01(){
        return new Person("username",20);
    }
}



  public class MainTest2 { 
    public static void main(String args[]){
    //Load the annotated configuration file         
        ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);    
        //Getting bean s from containers
        //Person person = (Person) app.getBean("person01");           
        //System.out.println(person);
        String[] namesForBean = app.getBeanNamesForType(Person.class);
        for(String name:namesForBean){
            System.out.println(name);
        }
    
    }
}


@ ComponentScan Scanning Rules

@Configuration
@ComponentScan(value="com.enjoy.cap2", includeFilters={        
        @Filter(type=FilterType.ANNOTATION, classes={Controller.class})        
}, useDefaultFilters=false)   
public class Cap2MainConfig {
    //Register a bean in the container with the type of the return value. 
    @Bean
    public Person person01(){
        return new Person("james",20);
    }
}
  1. value values indicate that all classes under this package are scanned
  2. includeFilters denote the use of custom filters, where useDefaultFilters should shield default filters for false before the custom ones take effect (demo denotes that only classes of Controller type are scanned)
  3. Another excludeFilters is to filter the specified classes under the default filter. Custom filters can be used. Implementations
    TypeFilter can be customized

@ ComponentScan value: Specifies the package to scan
excludeFilters = Filter [] Specifies what rules to exclude those components when scanning
includeFilters = Filter [] Specifies which components only need to be included in the scan
useDefaultFilters = false defaults to true, scan all components, and change to false
The scanning rules are as follows.
FilterType.ANNOTATION: According to Annotations
FilterType.ASSIGNABLE_TYPE: According to a given type; for example, according to BookService type
FilterType.ASPECTJ: Using ASPECTJ expressions
FilterType.REGEX: Specify using regular
FilterType.CUSTOM: Implement TypeFilter Interface by Writing Classes by Using Custom Rules

// An example of FilterType.CUSTOM, commonly used
First add a custom filter rule class: TestTypeFilter
@ComponentScan(value="com.enjoy.cap2",includeFilters={

    @Filter(type=FilterType.CUSTOM,classes={TestTypeFilter.class})

},useDefaultFilters=false)

@ scope annotation

In spring, the bean defaults to singleton, and @Scope ("prototype") is multi-instance.

//Multi-instance
@Scope("prototype")
@Bean
public Person person(){
    return new Person("username",20);
}
  • prototype: Multiple instances: IOC container startup does not call methods to create objects in the container, but
    Method creation objects are invoked every time they are retrieved
  • singleton: Single instance (default): IOC container startup calls method creation objects to be placed in IOC container
    Later, each intersection is taken directly from the container (understood as a map.get object)
  • Request: Mainly for WEB applications, create an instance of the same request
  • Session: Create an instance of the same session.

Lazy lazy loading

@ When lazy adds this annotation, the instance is loaded into the IOC container only when the getBean call is made.

@ Conditional conditional registration bean s

public class WinCondition implements Condition{
    
    /*
    *ConditionContext: Context (environment) in which conditions can be judged
    *AnnotatedTypeMetadata: Annotated information
    *
    */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // Is TODO a WINDOW System
        //Get the beanFactory being used by the IOC container
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //Get the current environment variables (including whether our operating system is WIN or LINUX?)
        Environment environment = context.getEnvironment();
        String os_name = environment.getProperty("os.name");
        if(os_name.contains("Windows")){
            return true;
        }
        return false;
    }
}

//Adding conditional annotations registers according to custom logic, and when true registers to containers
@Conditional(WinCondition.class)
@Bean("lison")
public Person lison(){
    System.out.println("Add to container lison.......");
    return new Person("Lison",28);
}

@ Import registered bean s

@Import(value = { Dog.class,Cat.class,JamesImportSelector.class,JamesImportBeanDefinitionRegistrar.class })


public class JamesImportSelector implements ImportSelector{
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata){
        //Beans that return the full class name
        return new String[]{"com.enjoy.cap6.bean.Fish","com.enjoy.cap6.bean.Tiger"};
    }
}

public class JamesImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    /*
    *AnnotationMetadata:Annotation information for the current class
    *BeanDefinitionRegistry:BeanDefinition Registration class
    *    Add all bean s that need to be added to the container.
    *    @Scope
    */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        boolean bean1 = registry.containsBeanDefinition("com.enjoy.cap6.bean.Dog");
        boolean bean2 = registry.containsBeanDefinition("com.enjoy.cap6.bean.Cat");
        //If Dog and Cat exist in our IOC container at the same time, create the Pig class and add it to the container
        //For beans we want to register, encapsulate beans.
        if(bean1 && bean2){
            RootBeanDefinition beanDefinition = new RootBeanDefinition(Pig.class);
            registry.registerBeanDefinition("pig", beanDefinition);
        }
    }

}

How to register components in containers:

  • 1,@Bean: [Components that import third-party classes or packages], such as Person's third-party classes, need to be used in our IOC container

  • 2. Packet scan + Component annotation (@ComponentScan: @Controller, @Service@Reponsitory)@
    Componet, which is generally written for our own classes, uses this

  • 3,@Import:[Quickly Import a Component to the Container] Note: @Bean is a bit simple

    A, @Import (component to be imported into the container): The container registers the component automatically, and the bean's id is the full class name.
    b,ImportSelector: An interface that returns an array of full-class names of components that need to be imported into the container
    ImportBean Definition Registrar: Components can be manually added to IOC containers. All beans can be registered using Bean Difinition Registry and James ImportBean Definition Registrar can implement ImportBean Definition Registrar interface.

  • 4. Use the FactoryBean (Factory bean) provided by Spring to register and implement the FactoryBean < T > interface. An instance of registration can be written in the implementation method getObject. Note: For example, if MyFactoryBean implements the FactoryBean < T > interface, getBean("myFactoryBean") obtains instances to implement instances in the getObject method, and getBean ("& myFactoryBean") implements MyFactoryBean instances, which can be found by looking at the source code logically.

Keywords: Java Spring Session xml Linux

Added by dhorn on Wed, 28 Aug 2019 07:26:22 +0300