0% found this document useful (0 votes)
3 views

SpringCore - Session2

The document explains the concept of bean scopes in Spring, detailing singleton and prototype scopes, and how to modify bean definitions in XML. It also covers the use of init-method and destroy-method attributes for bean initialization and cleanup, as well as autowiring modes including byName and byType for dependency injection. Examples are provided through Java classes and XML configurations to illustrate these concepts in practice.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SpringCore - Session2

The document explains the concept of bean scopes in Spring, detailing singleton and prototype scopes, and how to modify bean definitions in XML. It also covers the use of init-method and destroy-method attributes for bean initialization and cleanup, as well as autowiring modes including byName and byType for dependency injection. Examples are provided through Java classes and XML configurations to illustrate these concepts in practice.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Scope: Scope decides the lifecycle and visibility of the object in the container.

Possible values
are singleton, prototype, requestScope, sessionScope..

Default scope is “singleton” i.e only one instance will be created in the container.

Now change the bean definition in entities.xml as below to verify the singleton scope

Modify the App.java as shown below to verify the scope of the account bean object.

Account.java
—------------------
package com.raghtech.entities;

public class Account {


private int accNo;
private String holderName;
private int balance;

public Account() {
accNo=111;
holderName="John";
balance = 5000;
}

public int getAccNo() {


return accNo;
}

public void setAccNo(int accNo) {


this.accNo = accNo;
}

public String getHolderName() {


return holderName;
}

public void setHolderName(String holderName) {


this.holderName = holderName;
}

public int getBalance() {


return balance;
}

public void setBalance(int balance) {


this.balance = balance;
}
}

App.java
—-------------------

package org.example;

import com.raghtech.entities.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App


{
public static void main( String[] args )
{
ApplicationContext context = new
ClassPathXmlApplicationContext("entities.xml");
Account account = (Account) context.getBean("account");
String holderName = account.getHolderName();
System.out.println("Account Holder Name: "+holderName);
Account account1 = (Account)context.getBean("account");
if(account==account1) {
System.out.println("both are referring to the same object");
} else {
System.out.println("both are referring to different objects");

}
}
}

Even though we are asking for the account object a second time, it is passing the same object
reference created with the first request.

Now lets try by changing the scope to “prototype”

Entities.xml
—-----------------

<bean id="account" class="com.raghtech.entities.Account" scope="prototype"/>

And rerun the above program. We can see else part statement is printed now as per each
request it will create a new instance

init-method attribute:
If the requirement is acquiring the resources and initializing the bean as soon as it is
created, we can write a method and use init-method attribute to notify the container.

In our case we are defining init() method in Account.java class to intialize the members as
shown below:

public void init() {


System.out.println("In init method, initializing the instance variables");
this.accNo=1111;
holderName = "Smith";
balance=6000;
}

Add the init-method attribute in the bean definition in entities.xml file as shown in below:

<bean id="account" class="com.raghtech.entities.Account"


scope="prototype"
init-method="init"/>

destroy-method attribute:

destroy-method: Specifies the name of a method to be called when the bean is being
destroyed, allowing you to perform cleanup or release resources associated with the bean.

Add the below method to the Account.java class to perform the cleanup activity.

public void cleanup() {


System.out.println("performing cleanup activity");
}

Add the destroy-attribute to the bean definition in entities.xml as shown below:

<bean id="account" class="com.raghtech.entities.Account"


init-method="init"
destroy-method="cleanup"/>

Close the context object explicitly by writing the below statement in App.java as shown
below:

package org.example;

import com.raghtech.entities.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App


{
public static void main( String[] args )
{
ApplicationContext context = new
ClassPathXmlApplicationContext("entities.xml");
Account account = (Account) context.getBean("account");
String holderName = account.getHolderName();
System.out.println("Account Holder Name: "+holderName);
Account account1 = (Account)context.getBean("account");
if(account==account1) {
System.out.println("both are referring to the same object");
} else {
System.out.println("both are referring to different objects");
}

((ClassPathXmlApplicationContext)context).close();
}
}

Autowiring:

In Spring Framework, autowiring is a feature that allows the automatic injection of dependencies into a
Spring bean. Instead of manually configuring each dependency with setter methods or constructor
arguments, you can let Spring handle the wiring based on certain rules. Autowiring simplifies
configuration and reduces the amount of XML or Java-based configuration code needed.

There are several modes of autowiring in spring:

No autowiring (no): This is the default behavior. You need to wire the beans explicitly using <property>
or <constructor-arg> tags in XML configuration or using @Autowired annotation in Java configuration.

ByName (byName): Spring looks for a bean with the same name as the property that needs to be
autowired. If found, it injects that bean into the property.

ByType (byType): Spring looks for a single bean of the same type as the property. If exactly one bean is
found, it injects that bean into the property.

Constructor (constructor): Similar to byType, but it's used for constructor injection.

Autodetect (autodetect): This mode first tries byType autowiring. If it fails, it falls back to byName.

Let us see with an example.


Every account holder will have an address for future communication. We can define an Address bean to
hold the address details.

Address.java
—------------------
package org.raghtech.bank.model;

public class Address {


private String hno;
private String street;
private String city;

public Address() {
hno = "1-397";
street="Liberty Road";
city = "London";
}
public String getHno() {
return hno;
}

public void setHno(String hno) {


this.hno = hno;
}

public String getStreet() {


return street;
}

public void setStreet(String street) {


this.street = street;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}
}

Add this Address bean as one of the property in Account.java

Account.java
—-------------------------

package org.raghtech.bank.model;

public class Account {


private int accNo;
private String name;
private int balance;
private String accType;

private Address addr;


public Address getAddr() {
return addr;
}
public void setAddr(Address addr) {
this.addr = addr;
}
public Account() {
accNo = 1111;
name = "John";
balance = 5000;
accType = "Savings";
}
public int getAccNo() {
return accNo;
}
public void setAccNo(int accNo) {
this.accNo = accNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public String getAccType() {
return accType;
}
public void setAccType(String accType) {
this.accType = accType;
}
public void deposit(int amt) {
this.balance += amt;
}
public void init() {
System.out.println("Inside init method");
name = "Smith";
}
public void destroy() {
System.out.println("Inside destroy method to release
resources");
}
}

Using “byName” to inject Address bean into Account bean. Make the below change in
entities.xml file

<?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
https://www.springframework.org/schema/beans/spring-
beans.xsd">

<bean id="account"
class="org.raghtech.bank.model.Account"
init-method="init"
destroy-method="destroy"
autowire="byName"
/>
<bean id="addr" class="org.raghtech.bank.model.Address"/>
</beans>

Test this configuration in App.java (Main application)

App.java
—------------------------
package org.example;

import org.raghtech.bank.model.Account;
import org.raghtech.bank.model.Address;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new
ClassPathXmlApplicationContext("app-beans.xml");
Account acc = (Account) context.getBean("account");
System.out.println(acc.getName());
System.out.println(acc.getBalance());
acc.deposit(5000);
Address addr = acc.getAddr();
System.out.println(addr.getCity());
}
}

Using “byType” to inject Address bean into Account bean.

Make the below change in entities.xml file

<bean id="account"
class="org.raghtech.bank.model.Account"
init-method="init"
destroy-method="destroy"
autowire="byType"
/>

You might also like