I got a requirement to create bean from stdin. I know how to create object via new keyword, but I don't know how to create bean from stdin by spring feature such as dependency injection. Any help please?
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();
}
CodePudding user response:
You can use getBean()
method of ApplicationContext
class. But before that you need to declare class A
and B
as spring beans. Please refer below example:
Class A
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";
}
}
Now, you can use application context to create instances of above classes as shown in below example:
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);
}
}