先自定义一个注解:
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Section {
String name();
}
写一个类实现 BeanPostProcessor
@Component
public class MsgEventProcessor implements BeanPostProcessor {
public static Set<String> list = new HashSet<>();
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
if (methods != null) {
for (Method method : methods) { //这里是把加上这个注解方法的注解name值拿到放到Set集合中
Section myMsgEvent = AnnotationUtils.findAnnotation(method, Section.class);
if (myMsgEvent!=null){
list.add(myMsgEvent.name());
}
}
}
return bean;
}
}
启动项目可以了
再加一个点 springboot启动时候自动执行一个方法 在类中实现这个方法 重写run方法 在项目启动时候后会执行他
implements ApplicationRunner
@Override public void run(ApplicationArguments args) throws Exception { System.out.println("请开始你的表演"); }第二种方式项目启动时候执行方法(注解的方式)
@PostConstruct // 加上该注解项目启动时就执行一次该方法
public void sendMessage1() throws InterruptedException {
log.info("发送短信方法---- 1 执行开始");
}
本文介绍了如何在SpringBoot中自定义注解`Section`并利用`BeanPostProcessor`来处理带有该注解的方法,将注解的name值收集到集合中。此外,展示了两种方式实现应用启动时自动执行的方法:一种是通过实现`ApplicationRunner`接口,另一种是在方法上使用`@PostConstruct`注解。这些技巧在实际开发中用于初始化设置或执行特定任务。
561

被折叠的 条评论
为什么被折叠?



