如何从标准输入创建bean?

How to create bean from stdin?

我需要从 stdin 创建 bean。我知道如何通过 new 关键字创建对象,但我不知道如何通过 spring 特性(如依赖注入)从标准输入创建 bean。有什么帮助吗?

Object object;
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.startsWith("A")) {
     object = new A();
}
else if (input.startsWith("B")) {
     object = new B();
}

您可以使用 ApplicationContext class 的 getBean() 方法。但在此之前,您需要将 class AB 声明为 spring bean。请参考以下示例: Class一个

import org.springframework.stereotype.Component;

@Component //This annotation is used to declare this class as a bean
public class A {

    @Override
    public String toString() {
        return "A";
    }
}

Class B

import org.springframework.stereotype.Component;

@Component //This annotation is used to declare this class as a bean
public class A {

    @Override
    public String toString() {
        return "A";
    }
}

现在,您可以使用应用程序上下文创建上述 classes 的实例,如下例所示:

import java.util.Scanner;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

@Service //Declares this call a service
public class StdinService {

    @Autowired //Injecting application context
    ApplicationContext applicationContext;

    @PostConstruct
    public void demo() {
        Object object = null;
        try (Scanner scanner = new Scanner(System.in)) {
            String input = scanner.nextLine();
            if (input.startsWith("A")) {
                object = applicationContext.getBean(A.class); //Usage of getBean method
            } else if (input.startsWith("B")) {
                object = applicationContext.getBean(B.class);
            }
        }

        System.out.println(object);
    }
}