繁体   English   中英

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

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

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

我通常创建使用@Configuration类和@Bean方法相同类的豆类和使用@Component(及其衍生物@Controller,@Service,@Repository)让春天注入的注解类的一个bean。

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

例如具有:

@Component
public class MyClass{}

并在两个不同的bean中注入此类,例如:

@Autowired MyClass beanA;
@Autowired MyClass beanB;

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

在Spring中,除非另外指定,否则所有bean都具有singleton范围。 因此,在自动装配时会得到相同的实例。

如果需要新实例,则需要使用@Scope指定

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM