spring annotation usage ideas / methods

Recently, I got some tips when using spring annotation, which is hereby recorded for future reference.

Know about the notes and what they do

Find the corresponding annotation according to the scene, and then understand the description and usage of the annotation in detail - through the description of the annotation itself / official documents

This is illustrated with a small application scenario

Scenario: perform a task periodically during project initialization.

Find an annotation @ Scheduled annotation. I think it should be able to complete the scenario of regularly executing tasks.

Because "Scheduled" literally means "Scheduled, regular", we need to understand this annotation in detail.

Learn more about @ Scheduled

For the sake of convenience, you can learn directly in the specific project, and the built project will also be used for subsequent testing.

package com.xl.test.springtest.controller;

import org.springframework.scheduling.annotation.Scheduled;

public class ScheduledConfig {
	
	@Scheduled(fixedRate=5000)
	public void sche() {
		System.out.println("loop excuting............................");
	}
}

View annotation description

Annotation that marks a method to be scheduled

The annotation method can be executed regularly.

Pay attention to the following contents in the annotation description, and introduce the conditions (prerequisites) required for using the annotation

Processing of @Scheduled annotations is performed by registering a ScheduledAnnotationBeanPostProcessor. This can be done manually or, more conveniently, through the <task:annotation-driven/>element or @EnableScheduling annotation.

Executing @ Scheduled is accomplished by registering a ScheduledAnnotationBeanPostProcesso processor. You can complete the processor registration by configuring the @ enableshcheduling annotation.

The annotated method must expect no arguments. It will typically havea void return type; if not, the returned value will be ignored when called through the scheduler. 

The annotated method cannot have parameters, and if the return value is void, if it is not void, the return value will be ignored.

To sum up, the description of the annotation includes the introduction, premise and usage of the annotation

According to the annotation, another annotation @ enableshcheduling is required to complete the processor registration

Check the description of @ enableshcheduling annotation to understand the definition, usage, etc
package com.xl.test.springtest.controller;

import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
public class EnableScheConfig {

}

Enables Spring's scheduled task execution capability, similar tofunctionality found in Spring's <task:*> XML namespace. To be usedon @Configuration classes as follows: 
 @Configuration
 @EnableScheduling
 public class AppConfig {

     // various @Bean definitions
 }
This enables detection of @Scheduled annotations on any Spring-managedbean in the container. For example, given a class MyTask  package com.myco.tasks;

 public class MyTask {

     @Scheduled(fixedRate=1000)
     public void work() {
         // task execution logic
     }
 }
the following configuration would ensure that MyTask.work() is calledonce every 1000 ms:  @Configuration
 @EnableScheduling
 public class AppConfig {

     @Bean
     public MyTask task() {
         return new MyTask();
     }
 }
Alternatively, if MyTask were annotated with @Component, thefollowing configuration would ensure that its @Scheduled method isinvoked at the desired interval:  @Configuration
 @EnableScheduling
 @ComponentScan(basePackages="com.myco.tasks")
 public class AppConfig {
 }
Methods annotated with @Scheduled may even be declared directly within @Configuration classes:  @Configuration
 @EnableScheduling
 public class AppConfig {

     @Scheduled(fixedRate=1000)
     public void work() {
         // task execution logic
     }
 }

By default, will be searching for an associated scheduler definition: eithera unique org.springframework.scheduling.TaskScheduler bean in the context,or a TaskScheduler bean named "taskScheduler" otherwise; the same lookupwill also be performed for a java.util.concurrent.ScheduledExecutorServicebean. If neither of the two is resolvable, a local single-threaded defaultscheduler will be created and used within the registrar. 

When more control is desired, a @Configuration class may implement SchedulingConfigurer. This allows access to the underlying ScheduledTaskRegistrar instance. For example, the following exampledemonstrates how to customize the Executor used to execute scheduledtasks: 
 @Configuration
 @EnableScheduling
 public class AppConfig implements SchedulingConfigurer {

     @Override
     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
         taskRegistrar.setScheduler(taskExecutor());
     }

     @Bean(destroyMethod="shutdown")
     public Executor taskExecutor() {
         return Executors.newScheduledThreadPool(100);
     }
 }

Note in the example above the use of @Bean(destroyMethod="shutdown").This ensures that the task executor is properly shut down when the Springapplication context itself is closed. 

Implementing SchedulingConfigurer also allows for fine-grainedcontrol over task registration via the ScheduledTaskRegistrar.For example, the following configures the execution of a particular beanmethod per a custom Trigger implementation: 
 @Configuration
 @EnableScheduling
 public class AppConfig implements SchedulingConfigurer {

     @Override
     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
         taskRegistrar.setScheduler(taskScheduler());
         taskRegistrar.addTriggerTask(
             new Runnable() {
                 public void run() {
                     myTask().work();
                 }
             },
             new CustomTrigger()
         );
     }

     @Bean(destroyMethod="shutdown")
     public Executor taskScheduler() {
         return Executors.newScheduledThreadPool(42);
     }

     @Bean
     public MyTask myTask() {
         return new MyTask();
     }
 }

For reference, the example above can be compared to the following Spring XMLconfiguration: 
 <beans>

     <task:annotation-driven scheduler="taskScheduler"/>

     <task:scheduler id="taskScheduler" pool-size="42"/>

     <task:scheduled-tasks scheduler="taskScheduler">
         <task:scheduled ref="myTask" method="work" fixed-rate="1000"/>
     </task:scheduled-tasks>

     <bean id="myTask" class="com.foo.MyTask"/>

 </beans>
 
The examples are equivalent save that in XML a fixed-rate period is usedinstead of a custom Trigger implementation; this is because the task: namespace scheduled cannot easily expose such support. This isbut one demonstration how the code-based approach allows for maximum configurabilitythrough direct access to actual componentry.
Note: @EnableScheduling applies to its local application context only,allowing for selective scheduling of beans at different levels. Please redeclare @EnableScheduling in each individual context, e.g. the common root webapplication context and any separate DispatcherServlet application contexts,if you need to apply its behavior at multiple levels.

The above @ enableshcheduling annotation has many detailed descriptions, which can be summarized as follows:

  • According to the literal meaning of "enable periodic / scheduling / scheduling", you can guess the general functions of the host:
Enables Spring's scheduled task execution capability, 

Enable Spring's ability to perform tasks regularly.

  • Using the @ enableshcheduling annotation in the Configuration class @ Configuration, Spring will automatically enable the @ Scheduled annotation method in the bean s managed in the detection container and make it execute regularly!
package com.xl.test.springtest.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class EnableScheConfig {

}

There are two ways to include the class of the @ Scheduled annotation method into the Spirng container for management:

  1. Directly use the @ Bean annotation in the Configuration class @ Configuration to incorporate it into the Spring container, such as:
package com.xl.test.springtest.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class EnableScheConfig {
	
	 @Bean
     public ScheduledConfig task() {
         return new ScheduledConfig();
     }
}

Task class

package com.xl.test.springtest.controller;

import org.springframework.scheduling.annotation.Scheduled;


public class ScheduledConfig {
	
	@Scheduled(fixedRate=5000)
	public void sche() {
		System.out.println("loop excuting............................");
	}
}

perhaps

  1. @Annotate @ Component on the class where the Scheduled annotation method is located, such as:
package com.xl.test.springtest.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class EnableScheConfig {
}

Note that in this case, the component scanning path needs to be added. I add it to other parties here

If the @ ComponentScan annotation is not configured in the project, you need to add:

Task class

package com.xl.test.springtest.controller;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledConfig {
	
	@Scheduled(fixedRate=5000)
	public void sche() {
		System.out.println("loop excuting............................");
	}
}


The above two methods can be referred to: @Component @Bean @Configuration usage

  • @The Scheduled annotation can also be directly declared in the @ Configuration class
package com.xl.test.springtest.controller;

import java.util.Date;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class EnableScheConfig {
	
	@Scheduled(fixedRate=5000)
	public void sche() {
		System.out.println(new Date() + " : loop excuting............................");
	}
}

  • Other complex application scenarios are also described in the notes, which are omitted here...

Example demonstration verification

Full code:

package com.xl.test.springtest.controller;

import java.util.Date;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class EnableScheConfig {
	
	@Scheduled(fixedRate=5000) // Execute the sche() method every 5s!!
	public void sche() {
		System.out.println(new Date() + " : loop excuting............................");
	}
}


Start project / complete validation

@Scheduled has other parameters that can be configured besides fixedRate.

Keywords: Spring

Added by Chiaki on Tue, 21 Dec 2021 04:27:23 +0200