springboot 自定义注解启动扫描注解类信息

本文介绍了如何在SpringBoot中自定义注解`Section`并利用`BeanPostProcessor`来处理带有该注解的方法,将注解的name值收集到集合中。此外,展示了两种方式实现应用启动时自动执行的方法:一种是通过实现`ApplicationRunner`接口,另一种是在方法上使用`@PostConstruct`注解。这些技巧在实际开发中用于初始化设置或执行特定任务。

先自定义一个注解:

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   执行开始");    
}
 

 

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值