Using the prototype scope

As we have seen, the prototype scope is used to get a new instance of a bean every time when requested. To understand prototype, we will take the same bean class, EmailService, and we just need to change the value of the scope attribute for the emailService bean in application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="emailService" class="com.packt.springbean.EmailService"
scope="prototype" />

</beans>

The code used for the singleton scope will the same as before, while the output of the preceding code will be as follows:

Feb 09, 2018 7:03:20 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6fc6f14e: startup date [Fri Feb 09 07:03:20 IST 2018]; root of context hierarchy
Feb 09, 2018 7:03:20 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [application-context.xml]

Object of EmailService is Created !!!
Email Content : Hello, How are you? sent to [email protected]

Object of EmailService is Created !!!
Email Content : null sent to null

From output, the EmailService constructor is called two times, and gets a new instance for each getBean() method called. For the second instance, emailServiceInstanceB, we get a null value, because we haven't set any value for that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.176.80