spring注解使用思路/方法
最近在使用spring注解的时候得出点小心得,特此记录以便今后查阅。
大概了解有哪些注解且分别是干什么的
根据场景找到对应的注解然后详细的了解该注解的说明及使用方法—通过注解本身的说明/官方文档
这里结合一个小应用场景来说明
场景:在项目初始化的时候定期执行一个任务。
找到一个注解@Scheduled注解,感觉应该可以完成定期执行任务这个场景。
因为根据字面意思 “Scheduled”有 “安排、定期”之意,所以对该注解进行详细了解。
详细了解@Scheduled
为了方便起见,直接在具体的项目里面进行了解,搭好的项目也会用于后续的测试。
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............................");
}
}
查看注解说明
Annotation that marks a method to be scheduled
野鸡翻译:标注该注解的方法能够定期执行。
注意注解说明中的下面的内容,介绍了使用该注解需要的条件(前提)
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.
野鸡翻译:执行@Scheduled是通过注册一个ScheduledAnnotationBeanPostProcesso处理器来完成的。可以通过配置@EnableScheduling 注解来完成处理器的注册。
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.
该注解的方法不能有参数,并且返回值要是void,如果不是void 返回值将被忽略。
综上,注解的说明包含了注解的介绍、使用前提、用法等
根据注解的说明,需要另外一个注解 @EnableScheduling来完成处理器的注册
查看@EnableScheduling注解的说明,了解定义、使用方法等
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.
以上,@EnableScheduling注解的说明很多,很详细,总结起来有如下几点:
- 根据字面意思“启用定期/安排/调度”可以猜到该主机大致的功能:
Enables Spring's scheduled task execution capability,
启用Spring的定期执行任务的能力。
- 在配置类@Configuration中使用@EnableScheduling注解,Spring会自动启用侦查容器中管理的bean中带有 @Scheduled 注解方法,并且使其定期执行!
package com.xl.test.springtest.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class EnableScheConfig {
}
要将带有 @Scheduled 注解方法所在类纳入到Spirng容器进行管理有两种方法:
- 直接在配置类@Configuration中使用@Bean注解将其纳入Spring容器中,如:
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();
}
}
任务类
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............................");
}
}
或者
- @Scheduled 注解方法所在类上加上注解@Component,如:
package com.xl.test.springtest.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class EnableScheConfig {
}
注意,这种情况需要加上组件扫描路径,我这里是加在其他的方的
如果项目中没有配置@ComponentScan注解则需要加上:
任务类
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............................");
}
}
以上两种方法可参考:@Component @Bean @Configuration 用法
- @Scheduled 注解也可直接申明在@Configuration 类中
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............................");
}
}
- 其他跟复杂的应用场景在注解说明中也有说明,这里省略。。。
示例演示验证
完整代码:
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) // 每隔5s执行一次 sche()方法!!
public void sche() {
System.out.println(new Date() + " : loop excuting............................");
}
}
启动项目/完成验证
@Scheduled除了fixedRate之外还有其他参数可以配置。