Learn with best explanation

Coding tutorials and solutions

What is Bean in Spring

A bean is simple object which is instantiated, assembled, and managed by a Spring IoC container.

Scope of bean in Spring

When defining any object as bean you have an option to declare scope of bean. For example if you want to force spring to produce only single instance every time you define it's scope as singleton.

Types of Bean Scope

There are five types of bean scope in Spring, Three scopes are available only if we use the Web-Application. The request, session, and global session are the scopes used with the web-app.

  • Singleton
  • Prototype
  • Request
  • Session
  • Global session

Singleton

Singleton scope returns a single bean instance per Spring IoC container. This is the default scope type.

Prototype

Prototype scope returns a new bean instance every time when requested to create a bean.

Request

Request scope returns a single instance for every HTTP request.

Session

Session scope returns a single instance for the entire HTTP session.

Global session

Global session scope is equal to session scope on portlet-based web applications.

Following is the Bean with Prototype scope @Scope("prototype").


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class Customer {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}