Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 什么';向Spring引导应用程序添加初始化代码的正确方法是什么?_Java_Spring_Spring Boot - Fatal编程技术网

Java 什么';向Spring引导应用程序添加初始化代码的正确方法是什么?

Java 什么';向Spring引导应用程序添加初始化代码的正确方法是什么?,java,spring,spring-boot,Java,Spring,Spring Boot,TLDR:我希望我的Spring启动应用程序在启动时运行一些初始化代码。代码需要访问springbean和值 我正在编写一个Spring引导应用程序,它将同时使用队列中的多条消息。为此,它需要实例化多个使用者对象。Spring是否有一种很好的方法来实例化同一类的可配置数量的实例 我必须使用的队列客户端充当线程池。它为我提供的每个消费者对象创建一个线程。使用者对象一次只接收一条消息,在接收另一条消息之前,它们必须完全处理并确认该消息。消费者不是线程安全的,所以我不能只使用单实例 我考虑过下面的方法

TLDR:我希望我的Spring启动应用程序在启动时运行一些初始化代码。代码需要访问springbean和值


我正在编写一个Spring引导应用程序,它将同时使用队列中的多条消息。为此,它需要实例化多个使用者对象。Spring是否有一种很好的方法来实例化同一类的可配置数量的实例

我必须使用的队列客户端充当线程池。它为我提供的每个消费者对象创建一个线程。使用者对象一次只接收一条消息,在接收另一条消息之前,它们必须完全处理并确认该消息。消费者不是线程安全的,所以我不能只使用单实例

我考虑过下面的方法,但我觉得不合适。这看起来像是滥用了
@组件
注释,因为
初始值设定项
实例在构造之后没有被使用。有什么更好的方法

@Component
public class Initializer {

    public Initializer(ConsumerRegistry registry, @Value("${consumerCount}") int consumerCount) {
        for (int i = 0; i < consumerCount; i++) {
            // Each registered consumer results in a thread that consumes messages.
            // Incoming messages will be delivered to any consumer thread that's not busy.
            registry.registerConsumer(new Consumer());
        }
    }

}
@组件
公共类初始值设定项{
公共初始值设定项(ConsumerRegistry注册表,@Value(${consumerCount})int consumerCount){
对于(int i=0;i
一个
应用程序监听器将满足您的需要。它会在注册事件时收到通知,例如,当ApplicationContext就绪时。您将有权访问所有的bean和注射剂

@Component
public class StartupApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Inject
    private ConsumerRegistry registry;

    @Inject
    @Value("${consumerCount}")
    private int consumerCount;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        //do your logic
        for (int i = 0; i < consumerCount; i++) {
            // Each registered consumer results in a thread that consumes messages.
            // Incoming messages will be delivered to any consumer thread that's not busy.
            registry.registerConsumer(new Consumer());
        }
    }
}
@组件
公共类StartupApplicationListener实现ApplicationListener{
@注入
私人消费登记处;
@注入
@值(${consumerCount}”)
私人国际消费者账户;
@凌驾
ApplicationEvent上的公共无效(ApplicationReadyEvent事件){
//做你的逻辑
对于(int i=0;i
对于这个可能重复的线程池,您希望实现什么?我在问题中添加了更多详细信息。同时来自队列的消息?您使用的队列是rabbitmq、activemq还是kafka Streams?