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容器进行管理有两种方法:

  1. 直接在配置类@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............................");
	}
}

或者

  1. @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之外还有其他参数可以配置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
方法参数上使用自定义注解的作用是为了自定义参数检查和修改参数内容。可以通过使用aop和自定义注解来实现这个功能。具体实现思路如下: 1. 使用aop切面拦截到带有自定义注解A的接口参数,并通过反射获取注解A参数的类字段集合。检查字段集合上的注解,如果被另一个注解B标识,则将其存储起来。 2. 将接口传入的json转换为jsonObject,并按照与步骤1相同的格式组织字段名称。 3. 如果发现字段名称与步骤1中存储的字段名称相同,则说明此字段需要修改值,直接修改jsonObject的对应值。 4. 返回修改后的json。 例如,在示例代码中,可以使用自定义注解MethodLog来标识需要记录操作描述的方法。通过aop拦截到带有MethodLog注解方法,并获取注解中的参数信息。然后可以根据需求对参数进行修改,例如可以通过另一个注解来指定需要修改的字段及其修改内容。 请注意,使用自定义注解修改方法参数的功能只适用于post请求的接口。需要使用aop来实现参数拦截和修改的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [controller接口参数使用自定义注解修改传入值](https://blog.csdn.net/weixin_44807009/article/details/126686565)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Spring MVC 集成 AOP,自定义注解,在切面获得方法参数,以及自定义注解的参数。](https://blog.csdn.net/qq_27093465/article/details/78800100)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值