spring项目中自定义注解

发布时间 2023-12-22 16:46:20作者: hasome

使用 BeanPostProcessor

  • BeanPostProcessor 是 Spring 框架提供的一个接口,用于在 Spring 容器中对 Bean 进行后处理。
  • 自定义注解后,可以实现一个 BeanPostProcessor 实现类,在 BeanPostProcessor 的 postProcessAfterInitialization() 方法中,使用 ClassPathScanningCandidateResolver 类来扫描带有自定义注解的类,并将扫描到的类注册到 Spring 容器中。

自定义注解 MyAnnotation:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

实现类 MyBeanPostProcessor:

public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(MyAnnotation.class)) {
            // 将扫描到的类注册到 Spring 容器中
            ApplicationContext applicationContext = ApplicationContextUtils.getApplicationContext();
            applicationContext.getBeanFactory().registerSingleton(beanName, bean);
        }
        return bean;
    }
}

使用 @MyAnnotation

@MyAnnotation
public class MyBean {

    public void doSomething() {
        // ...
    }
}

获取到Bean:

ApplicationContext applicationContext = ApplicationContextUtils.getApplicationContext();

// 获取使用 @MyAnnotation 注解的 Bean
MyBean myBean = applicationContext.getBean(MyBean.class);

// 调用 Bean 的方法
myBean.doSomething();

使用 @ComponentScan

  • @ComponentScan 注解用于指定需要扫描的包。
  • 在 @ComponentScan 注解中,可以使用 includeFilters() 属性来指定需要扫描的注解

扫描使用@MyAnnotation

@SpringBootApplication
@ComponentScan(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = MyAnnotation.class))
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

获取Bean

ApplicationContext applicationContext = ApplicationContextUtils.getApplicationContext();

// 获取使用 @MyAnnotation 注解的 Bean
MyBean myBean = applicationContext.getBean(MyBean.class);

// 调用 Bean 的方法
myBean.doSomething();