In the Spring Framework, bean scope determines the lifecycle and visibility of a bean instance within the application context. There are several types of bean scopes in Spring, including singleton, prototype, request, session, and others.
Here's an example of how to define bean scopes using annotations in Spring:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class AppConfig {
@Bean
@Scope("singleton")
public MySingletonBean mySingletonBean() {
return new MySingletonBean();
}
@Bean
@Scope("prototype")
public MyPrototypeBean myPrototypeBean() {
return new MyPrototypeBean();
}
}
In this example, MySingletonBean is defined as a singleton bean using the @Scope("singleton") annotation, while MyPrototypeBean is defined as a prototype bean using the @Scope("prototype") annotation.
Singleton beans are created once per application context and are shared across the entire application. Prototype beans are created each time they are requested from the application context, so they are not shared and a new instance is created every time.
You can also use other scopes like @Scope("request") or @Scope("session") for web applications to create beans with request or session scope, respectively.
Note: It's important to note that the default scope for a bean in Spring is singleton, so if you don't specify a scope for a bean, it will be created as a singleton bean.