Junior — Middle
What methods can be used to modify or replace the scope of a Scope Bean in an application?
sobes.tech AI
Answer from AI
In the Spring Framework, the default scope of a Bean is singleton, but it can be changed in several ways:
- @Scope annotation — applied to the Bean class, specifying the desired scope, for example:
@Component
@Scope("prototype")
public class MyBean {
// ...
}
- XML configuration — in older configurations, you can specify the scope in the bean definition:
<bean id="myBean" class="com.example.MyBean" scope="prototype" />
- Programmatically via BeanDefinition — when registering a bean in the context, you can set the scope:
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MyBean.class);
beanDefinition.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE);
registry.registerBeanDefinition("myBean", beanDefinition);
- Using special scopes — such as request, session, application in web applications, which can be specified via @Scope or XML.
Thus, changing the scope is possible through annotations, XML configuration, or programmatically during bean registration in the Spring context.