In the spring 1.x era, there were no annotations, lots of XML configuration files and lots of bean tags written internally. Annotation, a new feature released in Java5, sets the stage for the spring update. Starting with Spring 2.x, Spring converts object IOC procedures in XML configuration into annotations. The core reason why Spring Boot makes application creation and integration with other frameworks so easy is that it greatly simplifies project configuration and maximizes the principle of “convention over configuration.” However, there are many kinds of annotations, but also can easily cause confusion, which has this article “SpringBoot advanced tutorial (64) annotations.”

To have a more comprehensive and clear understanding of SpringBoot annotations, you need to classify them into Spring annotations, Spring Web Annotations, SpringBoot Annotations, Spring Scheduling annotations, and annotation collection. Annotations can be roughly divided into five categories, among which the first four categories are selected from the four categories for easy understanding. The last one is a collection of annotations, which may contain the first four annotations.

VSpring annotations

In Spring Core annotations, I focus on the Spring Core annotations used in Spring DI and Spring IOC. As we all know, Spring DI and Spring IOC are the core concepts of the Spring framework. So introduce org. Springframework. Beans. Factory. The annotation and org., springframework. Context. The annotations in the annotation pack. There are many annotations in these two packages, so extract 15 of them.

Spring Core Annotations:

  • @Autowired
  • @Qualifier
  • @Bean
  • @Required
  • @Value
  • @DependsOn
  • @Lazy
  • @Lookup
  • @Primary
  • @Scope
  • @Profile
  • @Import
  • @ImportResource
  • @PropertySource
  • @PropertySources

Just org. Springframework. Context. The annotation this package below, annotation is the older, so it is difficult to list all annotations, for example, can only take some commonly used. The purpose and definition of other annotations will be given at the end of the article (try to be as complete as possible).

1.1 the @autowired

The @autowired annotation can be placed on a member variable, on a set method of a member variable, or on any method to automatically execute the current method. If the method has parameters, The IOC container automatically looks for parameters of the same type to pass values to.

It is important to be clear: @autoWired is Autowired by type. If you need to assemble by name, you need to use it with @qualifier.

1.1.1 Constructor injection

@RestController public class UserController { private UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; }}Copy the code

1.1.2 Setter method injection

@RestController public class UserController { private UserService userService; @Autowired public void setUserService(UserService userService) { this.userService = userService; }}Copy the code

1.1.3 Field reflection injection

@RestController
public class UserController {
    @Autowired
    private UserService userService;
}
Copy the code

1.2 @ the Qualifier

We already mentioned that @AutoWired assembles Spring beans by type. If the container have more the same type of bean, the framework will throw NoUniqueBeanDefinitionException, to prompt more satisfy the conditions of beans for automatic assembly. The program can’t decide which one to use. By assembling the @Qualifier annotation with the name of the particular Spring bean we want to use, the Spring framework can find the one we want from multiple beans of the same type that meet the assembly requirements.

@Component("studentInfo")
public class StudentInfo implements UserInfo {
    public String userName() {
        return "student";
    }
}

@Component("teacherInfo")
public class TeacherInfo implements UserInfo {
    public String userName {
        return "teacher";
    }
}

@Component
public class UserService {
    @Autowired
    @Qualifier("studentInfo")
    private UserInfo userInfo;

    //todo 
}
Copy the code

1.3 @ Bean

@Bean is a method-level annotation that is used primarily in the @Configuration annotation class, but also in the @Component annotation class. The id of the added bean is the method name.

@Configuration public class BeanConfig { @Bean public Person userInfo() { return new UserInfo("toutou", 18); }}Copy the code

This configuration is the same as the previous configuration in XML:

<bean id="userInfo" class="com.test. userInfo" > <property name="age" value="18"/> <property name="name" value= http://toutou.cnblogs.com"/> </bean>Copy the code

@ 1.4 Required

@ Required annotation is applied to the bean properties of setter method, it shows that the affected bean properties in the configuration must be placed in an XML configuration file, otherwise the container will be thrown a BeanInitializationException anomalies.

@Required
void setUserName(String name) {
    this.name = name;
}
Copy the code
The < bean class = "com. Test. The UserInfo" > < property name = "name" value = "please call me brother leader https://www.cnblogs.com/toutou/" / > < / bean >Copy the code

@ 1.5 Value

@value dynamically injects external values into the Bean. It can inject ordinary strings, Java system variables, expression results, other Bean properties, properties configured in configuration files *.properties or *.yml, file resources, URL resources, etc.

1.6 @ DependsOn

The Spring container loads beans in an indeterminate order, and the Spring framework does not have a specific load order logic specification. The @dependson annotation can be defined on classes and methods. For example, if component A is dependent on component B, then component B needs to be registered in the IOC container before component A.

public class FirstBean { @Autowired private SecondBean secondBean; } public class SecondBean { public SecondBean() { System.out.println("SecondBean init"); }}Copy the code
@Configuration public class BeanConfig { @Bean("firstBean") @DependsOn(value = { "secondBean" }) public FirstBean firstBean() { return new FirstBean(); } @Bean("secondBean") public SecondBean secondBean() { return new SecondBean(); }}Copy the code

1.7 @ Lazy

The @lazy annotation is used to indicate whether the bean needs Lazy loading. The Spring IoC container typically instantiates all singleton beans at startup. If you want Spring to lazily load A at startup and then uninitialize it when calling B, you can use the @lazy annotation.

public class FirstBean { public void test() { System.out.println("FirstBean Class"); } } public class SecondBean { public void test() { System.out.println("SecondBean Class"); }}Copy the code
@Configuration
public class AppConfig {

    @Lazy(value = true)
    @Bean
    public FirstBean firstBean() {
        return new FirstBean();
    }

    @Bean
    public SecondBean secondBean() {
        return new SecondBean();
    }
}
Copy the code

1.8 @ Lookup

The @lookup annotation is an annotation on a method. The annotated method is overridden, and the container calls the getBean() method of the BeanFactory to return a bean, depending on the type of its return value.

1.9 @ Primary

@primary is similar to @Qualifier. It is used to solve the problem of @autoWired having multiple beans of the same type in the container. Primary can be understood as the default preference, and multiple beans cannot be set at the same time.

@Component("studentInfo")
public class StudentInfo implements UserInfo {
    public String userName() {
        return "student";
    }
}

@Component("teacherInfo")
@Primary
public class TeacherInfo implements UserInfo {
    public String userName {
        return "teacher";
    }
}

@Component
public class UserService {
    @Autowired
    @Qualifier("studentInfo")
    private UserInfo userInfo;

    //todo
}
Copy the code

1.10 @ the Scope

The @scope annotation is a Scope in the Spring IoC container that has the following scopes: Basic scope Singleton (default scope), Prototype (multiple cases), Web scope (ReqeUST, Session, GlobalSession), custom scope

1.11 @ Profile

The purpose of the @profile annotation is to deal with multi-environment development, such as dev in the development environment and PROd in the production environment. The @Profile annotation can be used to enable different development environments to use different data sources. Before spring3.2, the @profile annotation was used on classes, and after spring3.2, it was used on methods

1.12 @ Import

@import is used to inject the specified class. The Import component ID defaults to the full class name of the component.

@Configuration public class ConfigA { @Bean public A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public B b() { return new B(); }}Copy the code

1.13 @ ImportResource

The @importResource annotation is used to import the Spring configuration file and validate the contents of the configuration file. (springmvc. XML, ApplicationContext.xml)

@Configuration
@ImportResource({"classpath*:applicationContext.xml"})
public class XmlConfiguration {
}
Copy the code

1.14 @ PropertySource

The @propertysource annotation loads the specified configuration file

@Configuration
@PropertySource("classpath:config.properties")
public class ProperySourceDemo implements InitializingBean {

    @Autowired
    Environment env;

    @Override
    public void afterPropertiesSet() throws Exception {
        setDatabaseConfig();
    }

    private void setDatabaseConfig() {
        DataSourceConfig config = new DataSourceConfig();
        config.setDriver(env.getProperty("jdbc.driver"));
        config.setUrl(env.getProperty("jdbc.url"));
        config.setUsername(env.getProperty("jdbc.username"));
        config.setPassword(env.getProperty("jdbc.password"));
        System.out.println(config.toString());
    }
}
Copy the code

1.15 @ PropertySources

@propertysources as the name suggests, you can specify multiple @propertysources to import configuration files.

@PropertySources({
  @PropertySource("classpath:config.properties"),
  @PropertySource("classpath:db.properties")
 })
 public class AppConfig {
  //todo...
 }
Copy the code

VSpring Web annotations

2.1 @ RequestBody

It is used to receive data from the JSON string passed from the front end to the back end.

@RestController @RequestMapping("/api/v1") public class UserController { @Autowired private UserService userService; @PostMapping("/user") public UserInfo createUser(@Valid @RequestBody UserInfo user) { return userService.save(user); }}Copy the code

2.2 @ RequestMapping

RequestMapping is an annotation that handles request address mapping, which can be used on a class or method. That is, it specifies which URL requests the controller can handle.

@Controller class UserController { @RequestMapping(value = "/user/index", method = RequestMethod.GET) String index() { return "index"; }}Copy the code

2.3 @ GetMapping

The @getMapping annotation maps Http GET requests to specific handler methods. It is a combined annotation, a shortcut to @requestMapping (method = requestMethod.get).

    @GetMapping("/users")
    public List<user> getAllUser() {
        //...
    }
    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId)
            throws ResourceNotFoundException {
        user user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("user not found for this id :: " + userId));
        return ResponseEntity.ok().body(user);
    }
Copy the code

2.4 @ PathVariable

@pathvariable is a new feature in spring3.0 that accepts the value of a placeholder in the request path

2.5 @ PostMapping

The @postMapping annotation maps HTTP POST requests to specific handler methods. It is a combined annotation, a shortcut to @requestMapping (method = requestMethod.post).

@PostMapping("/user/add")
public User addUser(@Valid @RequestBody User user) {
 return userRepository.save(user);
}
Copy the code

Other extensions: @putMapping, @deletemapping, @PatchMapping(these three are relatively used less, just mentioned.)

2.6 @ ControllerAdvice

Enhanced controller, for controller global configuration in the same place. It can be used to define @ExceptionHandler, @initBinder, and @ModelAttribute to handle global exception handling, global data binding, and global data preprocessing.

@ControllerAdvice(basePackages = {"com.toutou.controller"} )
public class GlobalControllerAdvice {
    @InitBinder
    public void dataBinding(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
    }
    @ModelAttribute
    public void globalAttributes(Model model) {
        model.addAttribute("msg", "Hello World!");
    }
    @ExceptionHandler(FileNotFoundException.class)
    public ModelAndView myError(Exception exception) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", exception);
        mav.setViewName("error");
        return mav;
    }
}
Copy the code

2.7 @ ExceptionHandler

@ExceptionHandler handles a class of exceptions uniformly, thereby reducing code duplication and complexity.

2.8 @ InitBinder

@initBinder only annotates methods in @Controller to register a binder initialization method for the Controller, which is valid only for the Controller.

2.9 @ ModelAttribute

The @modelAttribute annotation is used to bind the parameters of a method or the return value of a method to the specified model property and return it to the Web view.

2.10 @ ResponseBody

@responseBody converts the object returned by the controller method to Json via the appropriate converter and writes it to the body of the Response object.

2.11 @ Controller

@Controller is used to mark a class. The class it marks is a SpringMvc Controller object. The distribution handler scans the methods of the class that uses the annotation and checks if the method uses the @RequestMapping annotation.

2.12 @ RestController

@restController is equivalent to @Controller + @responseBody in Spring.

2.13 @ RequestParam

@requestParam binds request parameters to your controller’s method parameters (a springMVC annotation that receives normal parameters)

2.14 @ CrossOrigin

CrossOrigin supports cross-domain and can be used on controllers as well as methods.

@CrossOrigin(origins = "http://toutou.com", maxAge = 3600) @RequestMapping("/index") String index() { return "Hello World!" ; }Copy the code

VSpring Boot annotations

3.1 @ SpringBootApplication

@SpringBootApplication is the core annotation of the Sprnig Boot project to enable automatic configuration. Since @Configuration,@EnableAutoConfiguration, and @ComponentScan annotations are used together, SpringBoot provides a unified annotation @SpringBootApplication. That is, @SpringBootApplication=@Configuration + @EnableAutoConfiguration + @ComponentScan.

@springBootApplication // equals: @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args)  { SpringApplication.run(Application.class, args); }}Copy the code

Above code, is not a lot of concise.

3.2 @ EnableAutoConfiguration

Beans can be automatically registered based on JAR dependencies in your CLASspath, typically on classes or interfaces that try to automatically configure your Spring application based on jar dependencies you add. Automatically loads all the beans your application needs — this depends on Spring Boot looking it up in the classpath.

@EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

3.3 @ ConditionalOnClass, @ ConditionalOnMissingClass

3.4 @ ConditionalOnBean, @ ConditionalOnMissingBean

ConditionalOnBean // ConditionalOnMissingBean is instantiated when the given ConditionalOnBean does not exist / / when given the name of the class in the classpath, current Bean is instantiated @ ConditionalOnMissingClass / / when given the name of the class in the class path does not exist, the current Bean is instantiatedCopy the code

3.5 @ ConditionalOnProperty

ConditionalOnProperty can be used to determine whether configuration has been injected by the attribute values in the configuration file.

3.6 @ ConditionalOnResource

ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource: ConditionalOnResource This annotation supports passing in multiple variables,

3.7 @ ConditionalOnWebApplication, @ ConditionalOnNotWebApplication

@ ConditionalOnWebApplication main use is: when the Spring is a web service, just gives effect to the class of the annotations; Usually configuration classes; @ ConditionalOnNotWebApplication not web applications.

3.8 @ Conditional

The purpose of @Conditional is to make a judgment according to certain conditions and register the bean to the container if the conditions are met.

VSpring Scheduling annotations

4.1 @ Scheduled

@Scheduled can be added to a method as a trigger source.

@Scheduled(fixedDelay=1000)
public void doSomething() {
    //...
}
Copy the code

4.2 @ EnableScheduling

EnableScheduling is used on configuration classes to enable support for scheduled tasks (on class).

@configuration @enablesCheduling public class Schedulecfig {//... }Copy the code

4.3 @ Async

@async annotated methods, called asynchronous methods; When these methods are executed, they are executed in a separate thread, and the caller can proceed without waiting for it to complete. Sometimes we call special tasks that take time, and importantly, we don’t care what happens when they return. This is where asynchronous tasks of this kind are needed.

4.4 @ EnableAsync

The @enableAsync annotation enables Spring asynchronous method execution

@Schedules

Just like @scheduled, @schedules contains multiple @Scheduled annotations inside Schedules to indicate that a method can have multiple scheduling Settings.

V annotation set

@ComponentScan: automatically discovers scanned components for this class. If you scan a class with @Component, @Controller, @Service, etc., and register it as a Bean, you can automatically collect all Spring components, including the @Configuration class. We often use the @ComponentScan annotation to search for Beans, combined with the @AutoWired annotation to import. All Spring components can be collected automatically, including the @Configuration class. We often use the @ComponentScan annotation to search for Beans, combined with the @AutoWired annotation to import. If not, Spring Boot scans for classes that use @service, @repository annotations in the Boot package and its children.

@Repository: Using the @Repository annotation ensures that DAO or Repositories provides an exception translation. The DAO or Repositories class modified by this annotation will be found and configured by ComponetScan without providing an XML configuration entry for them.

Inject @inject: Equivalent to the default @autowired, but without the required attribute;

@Component: Component annotation. This annotation can be used when components are difficult to categorize.

JsonBackReference: Solve the nested external chain problem.

JsonIgnore: Some properties of Java bean are ignored during JSON serialization, which affects serialization and deserialization.

ConfigurationProperties: Spring Boot can map custom properties files, such as config.properties files, to entity beans using annotations.

@ ConditionalOnSingleCandidate: combination @ Conditional annotations, as specified in the class has only one Bean in the container, or there are multiple but at the same time open configuration is first selection.

@ ConditionalOnCloudPlatform: combination @ Conditional annotations, as specified in the cloud open configuration platform activation.

ConditionalOnJndi: combine @ConditionalJNDI annotations to enable configuration only when the specified JNDI exists.

ConditionalOnJava: incorporates the @Conditional annotation to enable configuration only when the Java JVM running is in the specified version range.

ConditionalOnExpression: combination @conditionalannotation, which is enabled only when the SpEL expression is true.

@WiselyConfiguration: Composite annotations can replace @Configuration and @ComponentScan

@transcational: Transaction processing

@target (elementtype.type): meta-annotation used to specify which member of the class the annotation modifies –> specifies the interception rule

@cacheable: data cache

ActiveProfiles: used to declare ActiveProfiles

@ RunWith: runner

Other reference/learning materials:

  • Spring Boot Annotations
  • Spring Boot Annotations – HowToDoInJava
  • Springboot annotations
  • Three notes for SpringBoot
  • Frequently Used Annotations in Spring Boot Applications
  • Spring MVC Annotations with Examples

V Source code address

Github.com/toutouge/ja…

About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \