spring项目中自定义注解
使用 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();
作者:hasome
出处:https://www.cnblogs.com/hasome/p/17921949.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)