[英]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.