Some commonly used annotations in springboot

@Configuration

The class marked by the annotation is javaconfig, and the class will be put into the container of the ioc,
which is the class marked with our annotation, which is equivalent to our previous configuration file

@Bean

I want to introduce components into the ioc container, generally written in the configuration class, the default is single instance.
The id of the component is the method name, and the type of the component is the return value type.

@Lazy: Set to lazy loading, use with @Bean, this class will only be loaded when the object is used

@Scope("prototype"): Set the scope of the class, the default is not to write a single instance

Scope parameter value:
singleton://single instance;
prototype://multi-instance;
request://a request to create an instance;
session://a session to create an instance;

@Configuration and @Bean testing:

/**
 * proxyBeanMethods参数:
 *          是否代理bean的方法
 *          Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
 *          Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
 *          组件依赖必须使用Full模式默认。其他默认是否Lite模式
 */
@Configuration(proxyBeanMethods = true)    //--标注这个类就是一个配置类,相当于我们以前编写的xml文件
public class MyConfig {
    
    


    @Bean    //向ioc工厂注入一个bean,默认单实例,id为方法名:person/ 类型为返回值类型:Person
    public Person person(){
    
    
        return new Person("张三",18);
    }

    @Bean   //作用同上
    public Pet pet(){
    
    
        return new Pet("大黄",3);
    }
}

result:
Insert picture description here

@Component、@Controller、@Service、@Repository

Works the same way we used to

@ComponentScan

It is the same as we used to configure the scan path in xml, as long as there is spring injection annotation in the scan path, then it can be injected.
This annotation has some other attributes: exclude those classes, do not scan and load those classes, and load them as long as the conditions are met

test:

@Configuration
@ComponentScan(
        includeFilters ={
    
    
                @ComponentScan.Filter(type= FilterType.ANNOTATION,classes = {
    
    Controller.class})
        },
        useDefaultFilters = false
        //excludeFilters用法同上,不演示
)
public class MyConfig01 {
    
    
}
  1. includeFilters: Let those loaded into the ioc container, if you want to use this, you must add useDefaultFilters = false below to take effect
  2. excludeFilters: Do not let those loaded into the ioc container
  3. The value of type:

The generic class FilterType of the type value has the following values:
ANNOTATION: use annotation filtering;
ASSIGNABLE_TYPE: use the given type;
ASPECTJ: use ASPECTJ expression;
REGEX: use regular expression;
CUSTOM: use custom rules, Need to provide a TypeFilter implementation class;

Custom filter:

//要实现TypeFilter接口,重写match方法
public class MyFilter implements TypeFilter {
    
    

    /**
     * metadataReader:读取当前正在扫描的类的信元数据;
     * metadataReaderFactory:可以获取其他任何类的元数据。
     * @return 是否加载进ioc的容器中
     * @throws IOException
     */
    @Override
    public boolean match(MetadataReader metadataReader,
                         MetadataReaderFactory metadataReaderFactory) throws IOException {
    
    
        //===================metadataReader的常用方法==============================
        // 获取当前类的注解元数据
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        // 获取当前正在扫描的类的元数据
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        // 获取当前类资源(类的路径)
        Resource resource = metadataReader.getResource();
        //=====================================================
        //测试:只要包含er的类,就不加在进ioc容器
        // 获取当前正在扫描的类的元数据
        ClassMetadata classMetadata1 = metadataReader.getClassMetadata();
        //获取名称
        String className = classMetadata1.getClassName();
        //判断并返回
        return className.contains("er");
    }
}

@Conditional(): Determine whether the component meets the conditions, meets the creation, and does not meet the creation

public @interface Conditional { Class<? extends Condition>[] value(); } This annotation parameter can put a lot of our custom judges, only need to write a class to integrate the Condition class and implement the method.


public class aaa implements Condition {
    
    
    /**
     *
     * @param conditionContext   当前应用的上下文环境。
     * @param annotatedTypeMetadata 标注了该注解的类的信息
     * @return true:符合条件。false:不符合条件
     */
    @Override
    public boolean matches(ConditionContext conditionContext,
                           AnnotatedTypeMetadata annotatedTypeMetadata) {
    
    
        return false;
    }
}
//======================================
@Conditional({
    
    xxx.class})
public class MyConfig01 {
    
    
}

This annotation also derives many sub-annotations:

@ConditionalOnBean: when there is a specified bean in the container @ConditionalOnClass: when there is a specified
class in the class path
@ConditionalOnExpression: based on the SpEL expression as the judgment condition
@ConditionalOnJava: based on the JVM version as the judgment condition
@ConditionalOnJndi: in JNDI lookup under the conditions specified existing location
@ConditionalOnMissingBean: in the case where the container is not specified in the Bean
@ConditionalOnMissingClass: under conditions when the class path is not specified class of
@ConditionalOnNotWebApplication: the current project is not under the conditions of the Web project
@ConditionalOnProperty: specified whether there is an attribute value specified
@ConditionalOnResource: is there a specified resource class path
@ConditionalOnSingleCandidate: Bean only when specified in a container, or in the case where a plurality of Bean to specify the preferred Bean

We can judge which classes can be injected based on these annotations and which classes cannot be injected.

@Import: Quickly import components into the container

@Import: The component will be automatically registered in the container, and the id default is the full class name;
annotation parameters:
class array: import all classes into the ioc container.
ImportSelector: Returns an array of the full class names of the components to be imported, the component names are full class names;
ImportBeanDefinitionRegistrar: Manually registers the Bean to the container, and the component names can be customized.

ImportSelector: Need to write a class to implement the ImportSelector interface and implement methods

public class MyImportSelector implements ImportSelector {
    
    
	/**
	*AnnotationMetadata :可以获取到标注了 @Import 注解类的所有注解信息;
	*/
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    
    
        return new String[0];
    }
}

ImportBeanDefinitionRegistrar: can customize the name of the component registered in the ioc container

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    
    

    /**
     * @param importingClassMetadata 获取到标注了@Import注解的所有信息
     * @param registry               BeanDefinition 注册类: 调用它的 registerBeanDefinition 方法将需要添加到容器中的 Bean 手工注册进来;
     * RootBeanDefinition:跟容器
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    
    
            registry.registerBeanDefinition("id", new RootBeanDefinition(xxx.class));
        }
    }
}

@ImportResource

Through this annotation, we can import the spring xml file we wrote into javaconfig, and then parse it according to the javaconfig format.
Suitable for use when xml project is converted to annotation project

@ConfigurationProperties(profix=“xxx”)

You can assign values ​​to javabeans through configuration files. As long as there is a configuration starting with xxx in our configuration file, the attribute names with the same names in this javabean will be automatically bound and assigned.
The binding configuration file can only be the application.properties file
. The javabean to be assigned must exist in the ioc container

properties file:

person.name=张三
person.age=19

javaBean class:

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    
    
    private String name;

    private Integer age;
	//...省略getset等方法
}

Result:
Insert picture description here
This will automatically bind the configuration file. Be careful, this javabean must exist in the ioc container to be bound.


It can also be used with:
@EnableConfigurationProperties()+ @ConfigurationProperties annotation.

@EnableConfigurationProperties(xxx.class): Function:
1. Load xxx.class into the ioc container
2. Turn on the data binding function of xxx

Guess you like

Origin blog.csdn.net/weixin_43431123/article/details/112845814