Skip to main content

JavaBeans vs Spring beans vs POJOs

JavaBeans vs Spring beans vs POJOs


JavaBeans:

At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. Specifically, classes that

  • 1) have public default (no argument) constructors
  • 2) allow access to their properties using accessor (getter and setter) methods
  • 3) implement java.io.Serializable

Spring Beans:

A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in Spring configuration files (or, more recently, with annotations), instantiated by Spring containers, and then injected into applications.

  

Note that Spring beans need not always be JavaBeans. Spring beans might not implement the java.io.Serializable interface, can have arguments in their constructors, etc.

This is the very basic difference between JavaBeans and Spring beans.


For more information, refer to the source of the above text, Shaun Abram's article JavaBeans vs Spring beans vs POJOs.



Spring Beans More (V.V.V):

@Bean and @Autowired do two very different things. The other answers here explain in a little more detail, but at a simpler level:

  • @Bean tells Spring 'here is an instance of this class, please keep hold of it and give it back to me when I ask'.

  • @Autowired says 'please give me an instance of this class, for example, one that I created with an @Bean annotation earlier'.

Does that make sense? In your first example, you're asking Spring to give you an instance of BookingService, but you're never creating one, so Spring has nothing to give you. In your second example, you're creating a new instance of BookingService, telling Spring about it, and then, in the main() method, asking for it back.

If you wanted, you could remove the two additional lines from the second main() method, and combine your two examples as below:

@SpringBootApplication
public class Application {

  @Autowired
  BookingService bookingService;

  @Bean
  BookingService bookingService() {
    return new BookingService();
  }

  public static void main(String[] args) {
    bookingService.book("Alice", "Bob", "Carol");
  }
}

In this case, the @Bean annotation gives Spring the BookingService, and the @Autowired makes use of it.

This would be a slightly pointless example, as you're using it all in the same class, but it becomes useful if you have the @Bean defined in one class, and the @Autowired in a different one.

.................End.................





Theory Dependency injection of Spring Bean ==>  https://github.com/jpssasadara/SpringBEANNN


Dependency injection of Spring Bean( which configured in XML file )  Using XML)=>

Dependency injection of Spring Bean ( which created since @compment/@Services/@Repository/etc..  annotation on top of the class ) Using Annotation)=>

(Bean creating under @Configuration / @SpringbootApplication... and dependency injection )
.........................................

 

Spring Bean Scopes Type


https://howtodoinjava.com/spring-core/spring-bean-scopes/
Spring framework, we can create beans in 6 inbuilt spring bean scopes and you can also define your custom bean scope as well. Out of these six scopes, four are available only if you use a web-aware ApplicationContextsingleton and prototype scopes are available in any type of IOC containers.
Table of Contents

1. Spring Bean Scope Types
    1.1. singleton scope
    1.2. prototype scope
    1.3. request scope
    1.4. session scope
    1.5. application scope
    1.6. websocket scope
2. Custom thread scope
3. Summary
In Spring, scope can be defined using spring bean @Scope annotation. Let’s quickly list down all six inbuilt bean scopes available to use in spring application context. These same scope apply to spring boot bean scope as well.
SCOPEDESCRIPTION
singleton (default)Single bean object instance per spring IoC container
prototypeOpposite to singleton, it produces a new instance each and every time a bean is requested.
requestA single instance will be created and available during complete lifecycle of an HTTP request.
Only valid in web-aware Spring ApplicationContext.
sessionA single instance will be created and available during complete lifecycle of an HTTP Session.
Only valid in web-aware Spring ApplicationContext.
applicationA single instance will be created and available during complete lifecycle of ServletContext.
Only valid in web-aware Spring ApplicationContext.
websocketA single instance will be created and available during complete lifecycle of WebSocket.
Only valid in web-aware Spring ApplicationContext.

1.1. singleton scope

singleton is default bean scope in spring container. It tells the container to create and manage only one instance of bean class, per container. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached instance.
Example of singleton scope bean using Java config –
@Component
//This statement is redundant - singleton is default scope
@Scope("singleton"//This statement is redundant
public class BeanClass {
}
Example of singleton scope bean using XML config –
<!-- To specify singleton scope is redundant -->
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="singleton" />
//or
<bean id="beanId" class="com.howtodoinjava.BeanClass" />

1.2. prototype scope

prototype scope results in the creation of a new bean instance every time a request for the bean is made by application code.
You should know that destruction bean lifecycle methods are not called prototype scoped beans, only initialization callback methods are called. So as developer, you are responsible for clean up prototype-scoped bean instances and any resource there hold.
Java config example of prototype bean scope –
@Component
@Scope("prototype")
public class BeanClass {
}
XML config example of prototype bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="prototype" />
As a rule, you should prefer to use the prototype scope for all stateful beans and the singleton scope for stateless beans.
To use beans in the request, session, application and websocket scopes, you need to register the RequestContextListener or RequestContextFilter.

1.3. request scope

In request scope, container creates a new instance for each and every HTTP request. So, if server is currently handling 50 requests, then container can have at most 50 individual instances of bean class. Any state change to one instance, will not be visible to other instances. These instances are destructed as soon as the request is completed.
Java config example of request bean scope –
@Component
@Scope("request")
public class BeanClass {
}
//or

@Component
@RequestScope
public class BeanClass {
}
XML config example of request bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="request" />

1.4. session scope

In session scope, container creates a new instance for each and every HTTP session. So, if server has 20 active sessions, then container can have at most 20 individual instances of bean class. All HTTP requests within single session lifetime will have access to same single bean instance in that session scope.
Any state change to one instance, will not be visible to other instances. These instances are destructed as soon as the session is destroyed/end on server.
Java config example of session bean scope –
@Component
@Scope("session")
public class BeanClass {
}

//or

@Component
@SessionScope
public class BeanClass {
}
XML config example of session bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="session" />

1.5. application scope

In application scope, container creates one instance per web application runtime. It is almost similar to singleton scope, with only two differences i.e.
  1. application scoped bean is singleton per ServletContext, whereas singleton scoped bean is singleton per ApplicationContext. Please note that there can be multiple application contexts for single application.
  2. application scoped bean is visible as a ServletContext attribute.
Java config example of application bean scope –
@Component
@Scope("application")
public class BeanClass {
}

//or

@Component
@ApplicationScope
public class BeanClass {
}
XML config example of application bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="application" />

1.6. websocket scope

The WebSocket Protocol enables two-way communication between a client and a remote host that has opted-in to communication with client. WebSocket Protocol provides a single TCP connection for traffic in both directions. This is specially useful for multi-user applications with simultaneous editing and multi-user games.
In this type of web applications, HTTP is used only for the initial handshake. Server can respond with HTTP status 101 (switching protocols) if it agrees – to handshake request. If the handshake succeeds, the TCP socket remains open and both client and server can use it to send messages to each other.
Java config example of websocket bean scope –
@Component
@Scope("websocket")
public class BeanClass {
}
XML config example of websocket bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="websocket" />
Please note that websocket scoped beans are typically singletons and live longer than any individual WebSocket session.

2. Custom thread scope

Spring also provide a non-default thread scope using class SimpleThreadScope. To use this scope, you must use register it to container using CustomScopeConfigurer class.
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
       <map>
            <entry key="thread">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>
Every request for a bean will return the same instance within the same thread.
Java config example of thread bean scope –
@Component
@Scope("thread")
public class BeanClass {
}
XML config example of thread bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="thread" />

3. Summary

Spring framework has provided six spring bean scopes and instances have different lifecycle span within each scope. As a developer, we must choose the scope of any container managed bean wisely. Also, we must take wise decisions when beans with different scopes refer each other.
Try to remember all above given information to answer any spring bean scope interview questions.
Happy Learning !!



1. Overview

In this quick tutorial, you'll learn about the different types of bean scopes in the Spring framework.

The scope of a bean defines the life cycle and visibility of that bean in the contexts in which it is used.
The latest version of Spring framework defines 6 types of scopes:
  • singleton
  • prototype
  • request
  • session
  • application
  • websocket
The last four scopes mentioned request, session, application and websocket are only available in a web-aware application.

2. Singleton Scope

Defining a bean with singleton scope means the container creates a single instance of that bean, and all requests for that bean name will return the same object, which is cached. Any modifications to the object will be reflected in all references to the bean. This scope is the default value if no other scope is specified.

Let's create a Person entity to exemplify the concept of scopes:
1
2
3
4
5
public class Person {
    private String name;
    // standard constructor, getters and setters
}
Afterwards, we define the bean with singleton scope by using the @Scope annotation:
1
2
3
4
5
@Bean
@Scope("singleton")
public Person personSingleton() {
    return new Person();
}
We can also use a constant instead of the String value in the following manner:
1
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
Now we proceed to write a test that shows that two objects referring to the same bean will have the same values, even if only one of them changes their state, as they are both referencing the same bean instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static final String NAME = "John Smith";
@Test
public void givenSingletonScope_whenSetName_thenEqualNames() {
    ApplicationContext applicationContext =
      new ClassPathXmlApplicationContext("scopes.xml");
    Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
    Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
    personSingletonA.setName(NAME);
    Assert.assertEquals(NAME, personSingletonB.getName());
    ((AbstractApplicationContext) applicationContext).close();
}
The scopes.xml file in this example should contain the xml definitions of the beans used:
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    <bean id="personSingleton" class="org.baeldung.scopes.Person" scope="singleton"/>   
</beans>

3. Prototype Scope

A bean with prototype scope will return a different instance every time it is requested from the container. It is defined by setting the value prototype to the @Scope annotation in the bean definition:

1
2
3
4
5
@Bean
@Scope("prototype")
public Person personPrototype() {
    return new Person();
}
We could also use a constant as we did for the singleton scope:
1
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
We will now write a similar test as before that shows two objects requesting the same bean name with scope prototype will have different states, as they are no longer referring to the same bean instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private static final String NAME = "John Smith";
private static final String NAME_OTHER = "Anna Jones";
@Test
public void givenPrototypeScope_whenSetNames_thenDifferentNames() {
    ApplicationContext applicationContext =
      new ClassPathXmlApplicationContext("scopes.xml");
    Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
    Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
    personPrototypeA.setName(NAME);
    personPrototypeB.setName(NAME_OTHER);
    Assert.assertEquals(NAME, personPrototypeA.getName());
    Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
    ((AbstractApplicationContext) applicationContext).close();
}
The scopes.xml file is similar to the one presented in the previous section while adding the xml definition for the bean with prototype scope:
1
<bean id="personPrototype" class="org.baeldung.scopes.Person" scope="prototype"/>

4. Web Aware Scopes

As mentioned, there are four additional scopes that are only available in a web-aware application context. These are less often used in practice.

The request scope creates a bean instance for a single HTTP request while session scope creates for an HTTP Session.
The application scope creates the bean instance for the lifecycle of a ServletContext and the websocket scope creates it for a particular WebSocket session.
Let's create a class to use for instantiating the beans:
1
2
3
4
5
public class HelloMessageGenerator {
    private String message;
     
    // standard getter and setter
}

4.1. Request Scope

We can define the bean with request scope using the @Scope annotation:

1
2
3
4
5
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestScopedBean() {
    return new HelloMessageGenerator();
}
The proxyMode attribute is necessary because, at the moment of the instantiation of the web application context, there is no active request. Spring will create a proxy to be injected as a dependency, and instantiate the target bean when it is needed in a request.
We can also use a @RequestScope composed annotation that acts as a shortcut for the above definition:
1
2
3
4
5
@Bean
@RequestScope
public HelloMessageGenerator requestScopedBean() {
    return new HelloMessageGenerator();
}
Next, we can define a controller that has an injected reference to the requestScopedBean. We need to access the same request twice in order to test the web specific scopes.
If we display the message each time the request is run, we can see that the value is reset to null, even though it is later changed in the method. This is because of a different bean instance being returned for each request.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Controller
public class ScopesController {
    @Resource(name = "requestScopedBean")
    HelloMessageGenerator requestScopedBean;
    @RequestMapping("/scopes/request")
    public String getRequestScopeMessage(final Model model) {
        model.addAttribute("previousMessage", requestScopedBean.getMessage());
        requestScopedBean.setMessage("Good morning!");
        model.addAttribute("currentMessage", requestScopedBean.getMessage());
        return "scopesExample";
    }
}

4.2. Session Scope

We can define the bean with session scope in a similar manner:

1
2
3
4
5
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionScopedBean() {
    return new HelloMessageGenerator();
}
There's also a dedicated composed annotation we can use to simplify the bean definition:
1
2
3
4
5
@Bean
@SessionScope
public HelloMessageGenerator sessionScopedBean() {
    return new HelloMessageGenerator();
}
Next, we define a controller with a reference to the sessionScopedBean. Again, we need to run two requests in order to show that the value of the message field is the same for the session.
In this case, when the request is made for the first time, the value message is null. But once, it is changed, then that value is retained for subsequent requests as the same instance of the bean is returned for the entire session.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Controller
public class ScopesController {
    @Resource(name = "sessionScopedBean")
    HelloMessageGenerator sessionScopedBean;
    @RequestMapping("/scopes/session")
    public String getSessionScopeMessage(final Model model) {
        model.addAttribute("previousMessage", sessionScopedBean.getMessage());
        sessionScopedBean.setMessage("Good afternoon!");
        model.addAttribute("currentMessage", sessionScopedBean.getMessage());
        return "scopesExample";
    }
}

4.3. Application Scope

The application scope creates the bean instance for the lifecycle of a ServletContext.

This is similar to the singleton scope but there is a very important difference with regards to the scope of the bean.
When beans are application scoped the same instance of the bean is shared across multiple servlet-based applications running in the same ServletContext, while singleton-scoped beans are scoped to a single application context only.
Let's create the bean with application scope:
1
2
3
4
5
6
@Bean
@Scope(
  value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator applicationScopedBean() {
    return new HelloMessageGenerator();
}
Analogously as for the request and session scopes, we can use a shorter version:
1
2
3
4
5
@Bean
@ApplicationScope
public HelloMessageGenerator applicationScopedBean() {
    return new HelloMessageGenerator();
}
Now, let's create a controller that references this bean:
1
2
3
4
5
6
7
8
9
10
11
12
13
@Controller
public class ScopesController {
    @Resource(name = "applicationScopedBean")
    HelloMessageGenerator applicationScopedBean;
    @RequestMapping("/scopes/application")
    public String getApplicationScopeMessage(final Model model) {
        model.addAttribute("previousMessage", applicationScopedBean.getMessage());
        applicationScopedBean.setMessage("Good afternoon!");
        model.addAttribute("currentMessage", applicationScopedBean.getMessage());
        return "scopesExample";
    }
}
In this case, value message once set in the applicationScopedBean will be retained for all subsequent requests, sessions and even for a different servlet application that will access this bean, provided it is running in the same ServletContext.

4.4. WebSocket Scope

Finally, let's create the bean with websocket scope:

1
2
3
4
5
@Bean
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator websocketScopedBean() {
    return new HelloMessageGenerator();
}
WebSocket-scoped beans when first accessed are stored in the WebSocket session attributes. The same instance of the bean is then returned whenever that bean is accessed during the entire WebSocket session.
We can also say that it exhibits singleton behavior but limited to a WebSocket session only.

5. Conclusion

We have demonstrated different bean scopes provided by Spring and what their intended usages are.

The implementation of this tutorial can be found in the GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.

Comments

Popular posts from this blog

Hibernate (Java) -- by jps sasadara

Observer Design Pattern & RxJava & @Async

JAVA uml Based cording <<< by jps sasadara >>>