Solon2 常用注解之 @Component 与 @ProxyComponent 的区别

发布时间 2023-04-17 12:49:08作者: 带刺的坐椅

在 Solon 提倡“克制”的原则下,托管组件分为:

  • 普通组件:
    • 主要由内核提供的:@Configuration、@Component、@Controller、@Remoting 注解的类
    • 其中 @Controller、@Remoting 支持函数拦截
  • 代理组件:
    • 主要由内核提供的:@ProxyComponent(需要 solon.proxy 插件提供支持)注解的类
    • 支持函数可拦截

1、区别

@ProxyComponent

  • 被代理(即类的外面又包了一层类,看不见的),支持函数可拦截。例如支持:@Tran、@Cache 等借助函数拦截实现的能力

支持函数可拦截:

@ProxyComponent
public class UserService{
    @Tran
    public void addUser(User user){
    
    }
}

@Component

  • 不支持函数可拦截
  • 支持特定形态自动处理
  • 支持函数提取
  • 支持 Bean、BeanWrap 订阅

支持特定形态自动处理:LifecycleBean、EventListener、Filter、RouterInterceptor、Handler、LoadBalance.Factory。例:EventListener 会自动注册 EventBus

@Component
public class DemoEventListener implements EventListener<DemoEvent>{
    @Override
    public void onEvent(DemoEvent event) throws Throwable{
        
    }
}

支持函数被提取:通过 aopContext.beanExtractorAdd(Scheduled.class, new ScheduledExtractor()) 直接提取组件的 @Scheduled 函数

@Component
public class DemoJob{
    @Scheduled
    public void job1() throws Throwable{
        
    }
}

支持Bean、BeanWrap 订阅:(订阅,也支持 @Configuration + @Bean 产生的)

//通过订阅获取多个 IXxx 实现的组件或Bean(要在容器扫描前,提前订阅)
aopContext.subBeansOfType(IXxx.class, bean->{

});

@Component
public class DemoBean1 implements IXxx{
    
}

@Component
public class DemoBean2 implements IXxx{
    
}

2、了解代理与拦截