java - Spring 框架: is possible to create two beans of the same @Component without @Configuration?

标签 java spring dependency-injection configuration autowired

我只是使用 Spring Web Apps 进行一些实验,以便更好地了解该框架的工作原理。

我通常使用@Configuration类和@Bean方法创建同一类的更多bean,并使用@Component(及其派生类< strong>@Controller、@Service@Repository),让 Spring仅注入(inject)带注释的类的单个 bean

我的问题是,是否可以在不使用@Configuration@Bean的情况下创建同一@Component类的更多bean?

例如有:

@Component
public class MyClass{}

并将此类注入(inject)两个不同的 bean,例如:

@Autowired MyClass beanA;
@Autowired MyClass beanB;

我尝试过这样做,当然我有两个实例指向内存中完全相同的 bean。

最佳答案

在 Spring 中,默认情况下所有 bean 都具有 singleton 作用域,除非另有指定。因此,当您 Autowiring 它时,您会得到相同的实例。

如果您想要一个新实例,则需要使用@Scope指定

@Component
@Scope("prototype")
public class MyClass{}

关于java - Spring 框架: is possible to create two beans of the same @Component without @Configuration?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49106917/

相关文章:

Java 任务运行时

java - 如何将ArrayList限制为15个?

dependency-injection - 将 DI 容器注入(inject)(几乎)每个类是一种反模式吗?

java - 使用 Guice,如何注入(inject)父类(super class)的构造函数参数?

java - 如何从 Android 向 Web 服务器发送多部分/表单数据?

java - 使用 String.replaceAll 进行简单洗牌的正则表达式

Spring 3.0 junit 测试 DispatcherServlet

java - Spring Boot - NoClassDefFoundError NioBlockingSelector$BlockPoller

Java Spring + Hibernate "Cannot add or update a child row"

c# - IoC/DI 容器、工厂和运行时类型创建