Solon v3.6.2

关于单例与原型 @Singleton

</> markdown

Solon 容器托管的对象,默认是单例的。也可以是原型的(即多例。每次获取或注入实例,会新构造实例)。

1、构建单例托管对象

  • @Component 组件注解(默认是单例)
@Component
public class DemoService{ }
  • @Bean 注解(只有单例)
@Configuration
public class DemoConfig {
   @Bean
   public DataSource db1(@Inject("${demo.db1}") HikariDataSource ds){
       return ds;
   }
}
  • 手动构建
Solon.context().wrapAndPut(DemoService.class);
//或
//Solon.context().wrapAndPut(DemoService.class, new DemoService());

2、构建原型(非单例)托管对象

Solon 的原型是实例级的,即每次获取或注入会构建新实例。(方法调用时,不会构建新实例)

  • @Component 组件注解(添加非单例注解声明)
@Singleton(false)
@Component
public class DemoService{ }
  • 手动构建
BeanWrap bw = Solon.context().wrap(DemoService.class);
bw.singletonSet(false);

Solon.context().putWrap(DemoService.class, bw)

3、只支持“单例”的几个内部接口

接口说明
org.noear.solon.core.bean.LifecycleBean带有生命周期接口的 Bean
org.noear.solon.core.event.EventListener本地事件监听,会自动注册 EventBus
org.noear.solon.core.LoadBalance.Factory负载平衡工厂
org.noear.solon.core.handle.Filter过滤器
org.noear.solon.core.route.RouterInterceptor路由拦截器
org.noear.solon.core.handle.EntityConverter请求实体转换器。//用于执行Mvc参数整体转换
org.noear.solon.core.handle.MethodArgumentResolver方法参数分析器。//用于执行Mvc单个参数分析
org.noear.solon.core.handle.ReturnValueHandler返回值处理器。//用于特定Mvc返回类型处理
org.noear.solon.core.handle.Render渲染器。//用于响应数据渲染输出