我只是使用 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/