简体   繁体   English

Spring Framework:是否可以在没有@Configuration的情况下创建具有相同@Component的两个bean?

[英]Spring Framework: is possible to create two beans of the same @Component without @Configuration?

I'm just doing some experiments with Spring Web Apps in order to learn better how the framework works. 我只是在使用Spring Web Apps做一些实验,以便更好地了解框架的工作原理。

I usually create more beans of the same class using @Configuration class and @Bean methods and use @Component (and its derivates @Controller , @Service , @Repository ) to let Spring inject only a single bean of the annotated class. 我通常创建使用@Configuration类和@Bean方法相同类的豆类和使用@Component(及其衍生物@Controller,@Service,@Repository)让春天注入的注解类的一个bean。

My question is, is that possible to create more beans of the same @Component class without using @Configuration and @Bean ? 我的问题是,是否可以在不使用@Configuration@Bean的情况下创建更多具有相同@Component类的bean

For instance having: 例如具有:

@Component
public class MyClass{}

and injecting this class in two different beans such as: 并在两个不同的bean中注入此类,例如:

@Autowired MyClass beanA;
@Autowired MyClass beanB;

I've tried doing so and OF COURSE I got two instances pointing at the exact same bean in memory. 我尝试这样做,当然我有两个实例指向内存中完全相同的bean。

In Spring by default all beans have singleton scope unless specified otherwise. 在Spring中,除非另外指定,否则所有bean都具有singleton范围。 Hence you get the same instance when you Autowire it. 因此,在自动装配时会得到相同的实例。

If you want a new instance you need to specify with @Scope 如果需要新实例,则需要使用@Scope指定

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring boot - 没有@component 注解的bean配置 - Spring boot - beans configuration without @component annotation 具有两个相同类型NoUniqueBeanDefinitionException的bean的Spring Configuration xml文件 - Spring Configuration xml file with two beans of the same type NoUniqueBeanDefinitionException Java中的Spring配置-创建和使用2个相同类的bean,而不使用Autowired - Spring configuration in Java - Create and use 2 beans of same class NOT using Autowired 如何根据Spring中的配置创建多个相同类型的bean? - How to create multiple beans of same type according to configuration in Spring? Spring Boot Application如何在没有@Configuration类的情况下创建bean - How does a Spring Boot Application create beans without @Configuration class 是否可以创建多个同名的 spring bean(来自不同的接口)? - is it possible to create multiple spring beans (from different interfaces) with the same name? 如何在 Spring Context 中创建两个相同类的 bean? - How can I create two beans of same class in a Spring Context? 是否可以在一个循环中创建 spring bean? - Is it possible to create spring beans in a cycle? Spring配置:2个具有相同类引用的bean - Spring Configuration: 2 beans with same class reference Spring创建了两个@Configuration bean启动 - Spring creates two of @Configuration beans starting up
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM