如何在动态时间内使用不同的参数创建bean

Yi Tian :

如果我有这样的课程:

@Service
@Scope("prototype")
public class TraderStarter {
private String address;
}

和TraderStarter应该创建X次,X由数据库动态确定。我应该如何获得这些豆子?只有这样吗?

@Component("SpringContextUtil")
public class SpringContextUtil implements ApplicationContextAware {
    private  static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
}

使用SpringContextUtil .getBean()并为每个原型TraderStarter设置参数?非常感谢。

马克·布拉姆尼克:

简而言之,prototype意味着将在每次对此bean的请求时创建新bean(注入到不同的类/ getBean调用中)。

因此,如果要创建这些原型bean,则有人会触发此过程。

当然,一种方法是使用ApplicationContextIMO 但这一种不好的方法,因为您的代码已与spring耦合。

您不能将原型注入到单例中,这是行不通的。但是,您可以使用javax.inject.Provider与Spring集成的接口:

这是一个例子:

// from your example
// you can use injection here and everything, its a regular spring bean
@Service 
@Scope("prototype")
public class TraderStarter {
  private String address;

  public void setAddress(String address) {
      this.address = address;
  }   
}   

///////////////////////
@Component 
public class MyDbManager {

    private Provider<TraderStarter> traderStarterProvider; 

    public List<TraderStarter> dynamicallyCreateBeans() {
           List<String> addresses = dbManager.findAllAddresses();// to to the db, get the data
           return 
                addresses.stream()
                .map(this::createTraderStarter)  // <-- creates different beans! 

                .collect(Collectors.toList());
    }

    private TraderStarter createTraderStarter(String address) {
        TraderStarter ts = provider.get();
        ts.setAddress(address);
        return ts;
    }    
}

工厂还有其他方法(请参见ObjectFactory)和创建代理(查找方法和作用域代理),但是IMO这是最干净的方法。

无论如何,如果您选择其他解决方案,请阅读本教程

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在一定时间内循环播放?

如何在设定的时间内递归调用函数?

如何在很长的毫秒时间内创建Java 8 LocalDate?

如何在有限的时间内通过pika使用RabbitMQ消息?

如何在更少的时间内创建动态类

如何在固定时间内返回下标?

在线性时间内使用邻接表创建顶点对

我如何在Keras的测试时间内使用批量标准化?

如何在特定时间内锁定Android设备?

如何在一定时间内运行代码?

如何在较短的时间内使用实体框架同时编辑1000条记录

如何在不同的指定时间内显示不同的组件?

如何在预定时间内发送报告

如何在碳日期时间内使用变量?

如何在指定时间内使用cassandra将数据导出到csv?

使用Rails如何在给定时间内查找用户预订的课程

如何在无限时间内使用随机函数生成随机图像?

QTcpSocket实例如何在间隔几秒钟的时间内多次使用?

如何在窗口ReplaySubject时间内使用TestScheduler

如何在更少的时间内重用伪类?

如何在更少的时间内使用我的vim配置?

如何在更少的时间内定义变量

如何在一段时间内使用管道?

如何在1个间隔时间内选择数据作为动态查询

如何在固定的时间内使用javascript函数?

如何在短时间内使用 python 从 Ubuntu 16.04 连接到 SQL Server 2016?

如何在有限的时间内呈现刺激并使用 Psychtoolbox 记录反应

如何在指定的时间内运行循环

如何在C中使用while循环在给定时间内运行