Spring common annotations

@Configuration

Appeared from spring3.0, it is equivalent to the xml file of configuring bean. This annotation can be used to realize the configuration based on java class (the other two ways can refer to this article: Spring summary (2) How to configure metadata-inject bean To the Spring container ).

The source code is as follows:

The class marked by this annotation will create an object and inject it into the IOC container.

Simple to use:

package spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import entity.Person;

@Configuration
public class Config {
  @Bean
  public Person person() {
    return new Person(18,"dreamcasher");
  }

  public static void main(String[] args) {
    //创建IOC容器,并将实例创建后注入到容器中
    ApplicationContext app = new AnnotationConfigApplicationContext(Config.class);
    Object person = app.getBean("person");
    System.out.println(person);
  }
}

operation result

@ComponentScan

According to the path of the custom scan package, inject the classes annotated with @Component, @Controller, @Service, and @Repository under the path into the spring container.

ps: Here is a record of a pit encountered during use. There is an attribute useDefaultFilters in the annotation. The default value is true. If the value is true, then the annotations such as @Controller, @Service, @Repository will be added during scanning. The class is injected into the spring container, so in general, if you want to use the includeFilters property, useDefaultFilters should be set to false.

@Lazy

The spring container will create a non-lazy loaded singleton during the startup process. The @Lazy annotated class will not be created during the startup of the spring container, but will be created when the spring container is started.

@Scope

You can set whether the bean is singleton or prototype. The default is singleton

@Conditional

After a certain general condition is met, the bean will be injected into the container. View the original code as follows:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Conditional {
    Class<? extends Condition>[] value();
}

The incoming class object needs to implement the Condition interface

@Import

The incoming class object can be injected into the container. There are no restrictions on the type, such as the class under the classes file, the class in the third-party package, or the class that implements the ImportBEANDefinitionRegistrar interface

@Autowired @Qualifier @Resource @Primary 

Use can refer to the article: @Resource and @Autowired comparison

Guess you like

Origin blog.csdn.net/qq_28411869/article/details/89314667