springboot使用自定义注解将对象注入容器中

在Spring Boot中,你可以通过自定义注解和Spring的`BeanPostProcessor`来将对象注入到Spring容器中。以下是一个简单的实现步骤:

1. **创建自定义注解**:

1
2
3
4
5
6
7
8
9
import java.lang.annotation.ElementType;
   import java.lang.annotation.Retention;
   import java.lang.annotation.RetentionPolicy;
   import java.lang.annotation.Target;
 
   @Target(ElementType.TYPE)
   @Retention(RetentionPolicy.RUNTIME)
   public @interface CustomComponent {
   }

  

2. **实现BeanPostProcessor**:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.springframework.beans.BeansException;
   import org.springframework.beans.factory.config.BeanPostProcessor;
   import org.springframework.stereotype.Component;
   import org.springframework.context.ApplicationContext;
   import org.springframework.context.ApplicationContextAware;
 
   @Component
   public class CustomComponentProcessor implements BeanPostProcessor, ApplicationContextAware {
 
       private ApplicationContext applicationContext;
 
       @Override
       public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
           if (bean.getClass().isAnnotationPresent(CustomComponent.class)) {
               // Register the bean in the application context
               ((ConfigurableApplicationContext) applicationContext).getBeanFactory().registerSingleton(beanName, bean);
           }
           return bean;
       }
 
       @Override
       public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
           this.applicationContext = applicationContext;
       }
   }

  

3. **使用自定义注解**:

1
2
3
4
@CustomComponent
   public class MyCustomBean {
       // Your custom bean logic
   }

  

通过以上步骤,你可以使用`@CustomComponent`注解来标记需要注入到Spring容器中的类。`CustomComponentProcessor`会在Spring初始化时自动处理这些类并将其注册到容器中。

posted @   iTao0128  阅读(110)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示