Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Dependency Injection

You're reading from   Java 9 Dependency Injection Write loosely coupled code with Spring 5 and Guice

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher Packt
ISBN-13 9781788296250
Length 246 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Nilang Patel Nilang Patel
Author Profile Icon Nilang Patel
Nilang Patel
Krunal Patel Krunal Patel
Author Profile Icon Krunal Patel
Krunal Patel
Arrow right icon
View More author details
Toc

How to define a bean scope


So, we understand the different scopes and their usage. Now it is time to see how we can use them in coding. We will mainly look at singleton and prototype bean scopes with examples. 

Spring provides two different ways to write an application: one is traditional XML metadata configuration, and the second is Java configuration using annotations. Let's look at how XML configuration is used.

XML metadata configuration

In Spring, bean configuration is declared in an XML file of our choice. This file is used by an IoC container to initialize the application context, and at the same time, all bean definitions are initialized based on the provided attribute. 

Using the singleton scope

The singleton scope is a very common scope used in major applications. Here, we will start to use the singleton scope. First, we will create a bean class named EmailService, which consists of a simple getter/setter method and Constructor method with a print statement:

package com.packt.springbean...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image