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

ADP assignment1-5

Uploaded by

Aman Kumar.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

ADP assignment1-5

Uploaded by

Aman Kumar.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Assignment - I

Topic: Inheritance & Interfaces in Java


Name: Akash Kumar N
Registration no: 2141014001
Section: 10 ( J )
Branch: BTech CSE

1. Define a class Employee with two instance variables: ● name,


salary and age and two member methods: ● setData(): set the
details of the person. ● displayData(): display the details of the
person. Now, create two objects of class Employee and initialize
one object value directly (by using the dot(.) operator name:
“Joseph”, salary: 65784.50 and age: 25 ). Accept your name
and age through the keyboard and set them to another object
using the setData() method. Now display both the member
variables using the displayData() method. Also, check who is
older.

public class Employee {


private String name;
private double salary;
private int age;

public void setData(String name, double salary,int age){


this.name=name;
this.salary=salary;
this.age = age;
}

public void displayData(){


System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
System.out.println("Age: "+age);
}

public static String whoIsOlder(Employee e1,Employee e2){


if(e1.age > e2.age){
return e1.name + " is Older";
} else if( e1.age < e2.age) {
return e2.name + " is Older";
} else {
return "Both are of same age";
}

public static void main(String args[]){


Employee e1 = new Employee();
e1.name = "Joseph";
e1.salary = 65784.50;
e1.age = 25;

Employee e2 = new Employee();


e2.setData("Simba",50123.6,21);

e1.displayData();
e2.displayData();

System.out.println(whoIsOlder(e1,e2));
}
OUTPUT:
2. In a supermarket each product has minimum details like
prodId, price, quantity that is used during the biling process.
Keeping this in mind prepare a class named as Product having
the member variables ● prodId, price, quantity ● a static
variable totalPrice Initialize the value of the product through a
parameterized constructor. It consists of a display() method to
display the value of instance variables. A person went to the
market and purchased 5 different products. Using the above
mentioned class, display the details of products that the person
has purchased. Also, determine how much total amount the
person will pay for the purchase of 5 products.
public class Product {
private int prodId;
private double price;
private int quantity;
private static double totalPrice = 0.0;

public Product(int prodId,double price,int quantity){


this.prodId=prodId;
this.price=price;
this.quantity=quantity;
}

public void display(){


System.out.println("Product Id: "+prodId);
System.out.println("Price: "+price);
System.out.println("Quantity: "+quantity);

public static void main(String args[]){


Product products[] = new Product[5];
for(int i=0;i<5;i++){
products[i] = new Product(100+i,26.0+2*i,2*i+1);
totalPrice+=products[i].price * products[i].quantity;
}
for(int i=0;i<5;i++){
products[i].display();
}
System.out.println("Total Price: "+totalPrice);

}
}
OUTPUT:

3. Define a class Deposit. The instance variables of the class


Deposit are mentioned below through constructors.
Constructors are overloaded with the following prototypes.
Constructor1: Deposit ( ) Constructor2: Deposit (long, int,
double) Constructor3: Deposit (long, int) Constructor4:
Deposit (long, double) Apart from constructors, the other
instance methods are (i) display ( ): to display the value of
instance variables, (ii) calcAmt( ): to calculate the total amount.
totalAmt = Principal + (Principal * rate * Time)/100;
public class Deposit {
private Long principle;
private Integer time;
private Double rate;
private Double TotalAmt;

public Deposit(){
this.principle= 0L;
this.time =0;
this.rate = 0.0;
this.TotalAmt= 0.0;

}
public Deposit(Long principle,Integer time,Double rate){
this.principle= principle;
this.time =time;
this.rate = rate;
this.TotalAmt= principle+(principle*rate*time)/100;
}

public Deposit(Long principle,Integer time){


this.principle= principle;
this.time =time;
this.rate = 0.0;
this.TotalAmt= principle+(principle*rate*time)/100;
}
public Deposit(Long principle,Double rate){
this.principle= principle;
this.time =0;
this.rate = rate;
this.TotalAmt= principle+(principle*rate*time)/100;
}

public void display(){


System.out.println("Principle: "+principle);
System.out.println("Time: "+time);
System.out.println("Rate: "+rate);

public void calAmt(){


System.out.println("Total Amount: "+TotalAmt);
}

public static void main(String args[]){


Deposit d1 = new Deposit();
Deposit d2 = new Deposit(12L,12);
Deposit d3 = new Deposit(13L,13.2);
Deposit d4 = new Deposit(26L,26,0.5);

d1.display();
d1.calAmt();
d2.display();
d2.calAmt();
d3.display();
d3.calAmt();
d4.display();
d4.calAmt()
}
}

OUTPUT:
4. Define a base class Employee with instance variable name,
age. The instance variables are initialized through constructors.
The prototype of the constructor is as below. Employee (string,
int) Define a derived class HR with instance variables Eid,
salary. The instance variables are initialized through
constructors. The prototype of the constructor is as below. HR
(string, int, int, double). Another instance method of the HR
class is DisplayDetails() to display the information of HR
details.

public class Employee {


protected String name;
protected int age;

public Employee(String name,int age){


this.name=name;
this.age = age;
}

class HR extends Employee{


private int EId;
private double salary;

public HR(String name, int age,int EId,double salary){


super(name,age);
this.name = name;
this.age = age;
this.EId=EId;
this.salary=salary;
}

public void DisplayDetails(){


System.out.println("Employee ID: "+EId);
System.out.println("Salary: "+salary);
}

public static void main(String args[]){


Employee e1 = new Employee("Joe",24);
HR h1 = new HR("Jonas",26,234,1200000);
h1.DisplayDetails();

OUTPUT:

5. Create an abstract class Marks with three instance variables


(markICP, markDSA, and percentage) and an abstract method
getPercentage(). Create two classes: CSE with instance variable
algoDesign, and NonCSE with instance variable
enggMechanics. Both classes inherit the abstract class Marks
and override the abstract method getPercentage(). The
constructor of class CSE takes the marks in three subjects
(markICP, markDSA, and algoDesign) as its parameters, and
the constructor of class NonCSE takes the marks in three
subjects (markICP, markDSA, and enggMechanics) as its
parameters. Create an object for each of the two classes and
print the percentage of marks for both students.

public abstract class Marks {


protected double markICP;
protected double markDSA;
protected double percentage;

abstract double getPercentage();


}
class CSE extends Marks{
private double algoDesign;

public CSE(double markICP, double markDSA,double algoDesign){


this.markICP = markICP;
this.markDSA=markDSA;
this.algoDesign=algoDesign;
}
@Override
double getPercentage() {
return ((markDSA+markICP+algoDesign)/300.0)*100.0;
}
}

class NonCSE extends Marks{


private double enggMechanics;

public NonCSE(double markICP, double markDSA, double


enggMechanics){
this.markICP=markICP;
this.markDSA=markDSA;
this.enggMechanics=enggMechanics;
}

@Override
double getPercentage() {
return ((markDSA+markICP+enggMechanics)/300.0)*100.0;
}

public static void main(String args[]){


CSE c1 = new CSE(96.2,100.0,84.0);
NonCSE c2 = new NonCSE(89.65,92.67,77.52);

System.out.printf("Percentage: %.2f%n",c1.getPercentage());
System.out.printf("Percentage: %.3f",c2.getPercentage());
}
}
OUTPUT:

6. Define an interface DetailInfo to declare methods display( )


& count( ). Another class Student contains a static data
member maxcount, instance member name & method
setter(String name) to assign the values to the instance variable
and getter( ) to display the name of a student, count the no. of
characters present in the name of the student.

public interface DetailInfo {


void display();

int count();
}
class Student implements DetailInfo{
private static int maxcount;
private String name;

void setter(String name){


this.name=name;
}

void getter(){
System.out.println("Name: "+name);
}

@Override
public void display() {
getter();
}
@Override
public int count() {
return name.length();
}

public static void main(String args[]){


Student s1 = new Student();
s1.setter("Jonathan");
s1.display();
System.out.println("No. of characters: "+s1.count());
}
}

OUTPUT:

7.Design a package that contains two classes: Student & Test.


The Student class has data members as name, roll and instance
methods inputDetails() & showDetails(). Similarly the Test
class has data members as mark1, mark2 and instance methods
inputDetails(), showDetails(), Student is extended by Test.
Another package carry interface Sports with 2 attributes
score1, score2. Find grand total mark & score in another class.

package studentpackage;

public class Student {


protected String name;
protected int roll;

public void inputDetails(String name, int roll) {


this.name = name;
this.roll = roll;
}

public void showDetails() {


System.out.println("Name: " + name);
System.out.println("Roll Number: " + roll);
}
}

package studentpackage;

public class Test extends Student {


protected int mark1;
protected int mark2;

public void inputDetails(String name, int roll, int mark1, int mark2) {
super.inputDetails(name, roll);
this.mark1 = mark1;
this.mark2 = mark2;
}

public void showDetails() {


super.showDetails();
System.out.println("Mark 1: " + mark1);
System.out.println("Mark 2: " + mark2);
}

public int getTotalMarks() {


return mark1 + mark2;
}
}

package sportspackage;

public interface Sports {


int score1 = 10;
int score2 = 20;
}

import studentpackage.Test;
import sportspackage.Sports;

public class TotalScoreCalculator implements Sports {


public static void main(String[] args) {
Test studentTest = new Test();
studentTest.inputDetails("Alice", 101, 85, 90);

studentTest.showDetails();

int academicTotal = studentTest.getTotalMarks();


System.out.println("Academic Total Marks: " + academicTotal);

int sportsTotal = score1 + score2;


int grandTotal = academicTotal + sportsTotal;
System.out.println("Sports Total Score: " + sportsTotal);
System.out.println("Grand Total (Academic + Sports): " + grandTotal);
}
}
OUTPUT:
Name: Alice
Roll Number: 101
Mark 1: 85
Mark 2: 90
Academic Total Marks: 175
Sports Total Score: 30
Grand Total (Academic + Sports): 205
Assignment - 2
Topic:Loose-Coupling,Exception Handling, Collections
in JAVA and Simple Spring Programs

1. Show Loose coupling in JAVA by using the followings:


a) Interface= Keyboard b) class DellKeyboard= implements
Keyboard c) class LenovoKeyboard= implements Keyboard
d)class Computer=defines method “public void
keyboardUsed(DellKeyboard dk)”

interface Keyboard {
void type();
}

class DellKeyboard implements Keyboard {


@Override
public void type() {
System.out.println("Typing with Dell Keyboard.");
}
}

class LenovoKeyboard implements Keyboard {


@Override
public void type() {
System.out.println("Typing with Lenovo Keyboard.");
}
}

class Computer {
public void keyboardUsed(Keyboard keyboard) {
keyboard.type();
}
}
public class LooseCouplingDemo {
public static void main(String[] args) {
Computer computer = new Computer();

Keyboard dellKeyboard = new DellKeyboard();


Keyboard lenovoKeyboard = new LenovoKeyboard();

computer.keyboardUsed(dellKeyboard);
computer.keyboardUsed(lenovoKeyboard);
}
}

2. Show Loose coupling in JAVA by using the followings: a)


Interface= Vehicle b) class Bike= implements Vehicle c) class
Car= implements Vehicle d) class traveller=defines method
“public void travellerVehicleName()

interface Vehicle {
String getName();
}
class Bike implements Vehicle {
@Override
public String getName() {
return "Bike";
}
}

class Car implements Vehicle {


@Override
public String getName() {
return "Car";
}
}
class Traveller {
private Vehicle vehicle;

public Traveller(Vehicle vehicle) {


this.vehicle = vehicle;
}

public void travellerVehicleName() {


System.out.println("Traveller is using a " + vehicle.getName());
}
}
public class LooseCouplingDemo2 {
public static void main(String[] args) {
Vehicle bike = new Bike();
Vehicle car = new Car();

Traveller traveller1 = new Traveller(bike);


Traveller traveller2 = new Traveller(car);

traveller1.travellerVehicleName();
traveller2.travellerVehicleName();
}
}

3. Execute Java Exception Handling programs using try-catch


statement(s) to handle the exceptions: a) ArithmeticException
b) NullPointerException c) NumberFormatException d)
ArrayIndexOutOfBoundsException

public class ExceptionHandlingDemo {


public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
try {
int number = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " +
e.getMessage());
}
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
}
}

4. Execute small JAVA collection programs for the followings:


a) List b) Queue c) Set

import java.util.*;

public class CollectionExamples {


public static void main(String[] args) {

List<String> list = new ArrayList<>();


list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("List: " + list);

Queue<String> queue = new LinkedList<>();


queue.add("First");
queue.add("Second");
queue.add("Third");
System.out.println("Queue: " + queue);
System.out.println("Removed from Queue: " + queue.poll());
Set<String> set = new HashSet<>();
set.add("Dog");
set.add("Cat");
set.add("Bird");
System.out.println("Set: " + set);
}
}

OUTPUT:

5. Write a simple Spring Application, which will print "Hello


World!" or any other message based on the configuration done
in Spring Beans Configuration file

<!-- beans.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">

<!-- Define a bean for HelloWorld -->


<bean id="helloWorld" class="HelloWorld">
<property name="message" value="Hello, World!" />
</bean>
</beans>

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorld {


private String message;
public void setMessage(String message) {
this.message = message;
}

public void printMessage() {


System.out.println(message);
}
}

public class SpringAppDemo {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.printMessage(); // Output: Hello, World!
}
}

OUTPUT:
Hello, World!
Assignment - 3
Topic: Creating a Maven Project, Defining a POJO
Class, Generating runtime object using Spring IoC and
Injecting Dependencies.

1. Write a POJO class named Person with the following


details
a. Name (String)
b. Age (int)
c. City (String)
d. Phone number (List)

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Person {


private String name;
private int age;
private String city;
private List<String> phoneNumbers;

// Getters and Setters


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

public int getAge() { return age; }


public void setAge(int age) { this.age = age; }

public String getCity() { return city; }


public void setCity(String city) { this.city = city; }

public List<String> getPhoneNumbers() { return phoneNumbers; }


public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers; }

// Main method for testing


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Person person = new Person();
System.out.print("Enter name: ");
person.setName(scanner.nextLine());

System.out.print("Enter age: ");


person.setAge(scanner.nextInt());
scanner.nextLine(); // consume newline

System.out.print("Enter city: ");


person.setCity(scanner.nextLine());

person.setPhoneNumbers(new ArrayList<>());
System.out.print("Enter phone numbers (comma-separated): ");
String[] numbers = scanner.nextLine().split(",");
for (String num : numbers) {
person.getPhoneNumbers().add(num.trim());
}

// Print details
System.out.println("Person Details:");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
System.out.println("Phone Numbers: " + person.getPhoneNumbers());
}
}

OUTPUT:

2. Write a Java Program to create a class Student with the


following instance members: -
a. Student ID (int)
b. Student Name (String)
c. Student Branch (String)
d. Student Phone Numbers (List)
e. Student Course name with fees (Map)
Use setter and getter methods to initialize and fetch the
details. Using Spring Core - IoC, inject the Object using
XML Configuration.

import java.util.List;
import java.util.Map;

public class Student {


private int studentId;
private String studentName;
private String studentBranch;
private List<String> phoneNumbers;
private Map<String, Integer> courseFees;

// Getters and Setters


public int getStudentId() { return studentId; }
public void setStudentId(int studentId) { this.studentId = studentId;
}

public String getStudentName() { return studentName; }


public void setStudentName(String studentName) {
this.studentName = studentName; }

public String getStudentBranch() { return studentBranch; }


public void setStudentBranch(String studentBranch) {
this.studentBranch = studentBranch; }

public List<String> getPhoneNumbers() { return phoneNumbers; }


public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers; }

public Map<String, Integer> getCourseFees() { return courseFees; }


public void setCourseFees(Map<String, Integer> courseFees) {
this.courseFees = courseFees; }

public void displayDetails() {


System.out.println("Student ID: " + studentId);
System.out.println("Name: " + studentName);
System.out.println("Branch: " + studentBranch);
System.out.println("Phone Numbers: " + phoneNumbers);
System.out.println("Courses and Fees: " + courseFees);
}
}

<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">

<!-- Define Student bean with dependency injection -->


<bean id="student" class="Student">
<property name="studentId" value="123" />
<property name="studentName" value="John Doe" />
<property name="studentBranch" value="CSE" />
<property name="phoneNumbers">
<list>
<value>1234567890</value>
<value>0987654321</value>
</list>
</property>
<property name="courseFees">
<map>
<entry key="Java" value="5000" />
<entry key="Python" value="4500" />
</map>
</property>
</bean>
</beans>

3. Write a Java Program to create a class Employee and


Address with the following instance members: -
a. class Employee
i. Employee ID (int)
ii. Employee Name (String)
iii. Employee Department (String)
iv. Employee Address (Reference type)
b. Class Address
i. Street (String)
ii. City (String)
iii. State (String)
iv. Pin code (int)
Using Spring IoC, Constructor approach to inject the
Object.
public class Employee {
private int employeeId;
private String employeeName;
private String employeeDepartment;
private Address address;

// Constructor for injection


public Employee(int employeeId, String employeeName, String
employeeDepartment, Address address) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeDepartment = employeeDepartment;
this.address = address;
}

public void display() {


System.out.println("Employee ID: " + employeeId);
System.out.println("Name: " + employeeName);
System.out.println("Department: " + employeeDepartment);
System.out.println("Address: " + address);
}
}

public class Address {


private String street;
private String city;
private String state;
private int pinCode;

// Constructor for injection


public Address(String street, String city, String state, int pinCode) {
this.street = street;
this.city = city;
this.state = state;
this.pinCode = pinCode;
}

@Override
public String toString() {
return street + ", " + city + ", " + state + " - " + pinCode;
}
}

<bean id="address" class="Address">


<constructor-arg value="123 Main St" />
<constructor-arg value="New York" />
<constructor-arg value="NY" />
<constructor-arg value="10001" />
</bean>

<bean id="employee" class="Employee">


<constructor-arg value="101" />
<constructor-arg value="Alice" />
<constructor-arg value="Engineering" />
<constructor-arg ref="address" />
</bean>

4. Write a Java Program to create a class Customer with


the following instance members: -
a. Customer Name (String)
b. Customer Phone Number (List)
c. Customer Email ID (String)
Using Spring IoC, Annotation approach to inject the
Object

import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class Customer {
private String name;
private List<String> phoneNumbers;
private String emailId;

// Getters and Setters


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

public List<String> getPhoneNumbers() { return phoneNumbers; }


public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers; }

public String getEmailId() { return emailId; }


public void setEmailId(String emailId) { this.emailId = emailId; }

public void displayDetails() {


System.out.println("Customer Name: " + name);
System.out.println("Phone Numbers: " + phoneNumbers);
System.out.println("Email ID: " + emailId);
}
}
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplication
Context;

public class CustomerApp {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Customer customer = context.getBean(Customer.class);
customer.displayDetails();
}
}

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}

5. Write a simple Spring Application, to understand the life


of beans.

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class LifecycleBean implements InitializingBean,


DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean is initialized!");
}

@Override
public void destroy() throws Exception {
System.out.println("Bean is destroyed!");
}

public void printMessage() {


System.out.println("Hello from LifecycleBean!");
}
}

<bean id="lifecycleBean" class="LifecycleBean" />


Assignment - 4
Topic: SpringBoot Starter, SpringBoot Starter
Dependencies and Auto Configuration,
Annotation-Based Java Configuration, Xml-Based
Configuration, Loosely Coupled Dependency Injection

1. Write a Java Program to show Loosely Coupling using


Spring XML configuration and Constructor-based Dependency
Injection using the following: a. PaymentMethod Interface b.
CreditCard Class implements the PaymentMethod Interface c.
PayPal Class implements the PaymentMethod Interface d.
ShoppingCart Class uses the PaymentMethod instance to
process payments. e. App Class to run the application.

public interface PaymentMethod {


void processPayment(double amount);
}

public class CreditCard implements PaymentMethod {


@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
public class PayPal implements PaymentMethod {
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}

public class ShoppingCart {


private final PaymentMethod paymentMethod;
// Constructor for dependency injection
public ShoppingCart(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}

public void checkout(double amount) {


System.out.println("Starting checkout...");
paymentMethod.processPayment(amount);
System.out.println("Checkout completed.");
}
}

<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">

<!-- Define CreditCard bean -->


<bean id="creditCard" class="CreditCard" />

<!-- Define PayPal bean -->


<bean id="payPal" class="PayPal" />

<!-- Inject CreditCard or PayPal into ShoppingCart using constructor-based


DI -->
<bean id="shoppingCart" class="ShoppingCart">
<constructor-arg ref="creditCard" />
<!-- To use PayPal instead, you can replace 'creditCard' with 'payPal' -->
</bean>
</beans>
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {


public static void main(String[] args) {
// Load the Spring configuration file
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");

// Retrieve the ShoppingCart bean from the Spring container


ShoppingCart shoppingCart = (ShoppingCart)
context.getBean("shoppingCart");

// Perform checkout using the injected PaymentMethod


shoppingCart.checkout(100.0);
}
}

OUTPUT:
Starting checkout...
Processing credit card payment of $100.0
Checkout completed.

2. Write a Java Program showing setter-based dependency


injection with reference in XML Configuration using the
following. a. EmailService class with a method
sendEmail(String msg)() b. SMSService class with a method
sendSMS(String msg)() c. NotificationService depends on both
the above classes with setter methods.

public class EmailService {


public void sendEmail(String msg) {
System.out.println("Email sent with message: " + msg);
}
}

public class SMSService {


public void sendSMS(String msg) {
System.out.println("SMS sent with message: " + msg);
}
}
public class NotificationService {
private EmailService emailService;
private SMSService smsService;

// Setter for EmailService


public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}

// Setter for SMSService


public void setSmsService(SMSService smsService) {
this.smsService = smsService;
}

public void notifyByEmail(String msg) {


emailService.sendEmail(msg);
}

public void notifyBySMS(String msg) {


smsService.sendSMS(msg);
}
}

<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">

<!-- Define EmailService bean -->


<bean id="emailService" class="EmailService" />

<!-- Define SMSService bean -->


<bean id="smsService" class="SMSService" />

<!-- Define NotificationService bean and inject dependencies via setters -->
<bean id="notificationService" class="NotificationService">
<property name="emailService" ref="emailService" />
<property name="smsService" ref="smsService" />
</bean>
</beans>

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {


public static void main(String[] args) {
// Load the Spring configuration file
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");

// Retrieve the NotificationService bean


NotificationService notificationService = (NotificationService)
context.getBean("notificationService");

// Use the notification service to send messages


notificationService.notifyByEmail("Hello via Email!");
notificationService.notifyBySMS("Hello via SMS!");
}
}

OUTPUT:
Email sent with message: Hello via Email!
SMS sent with message: Hello via SMS!

3. Write a Java Program to demonstrate annotation-based Java


configuration a. UserRepository class with a method saveUser()
b. UserService class depending on the above class with a setter
method DI.

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
public void saveUser() {
System.out.println("User saved to database.");
}
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
private UserRepository userRepository;

// Setter for dependency injection


@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}

public void registerUser() {


userRepository.saveUser();
}
}

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "your.package.name")
public class AppConfig {
}

import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext
;
public class App {
public static void main(String[] args) {
// Load the Spring application context
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);

// Retrieve the UserService bean


UserService userService = context.getBean(UserService.class);

// Use the UserService to register a user


userService.registerUser();
}
}

OUTPUT:
User saved to database.

4. Write a Java Program to demonstrate a simple example


using with annotation-based configuration in Spring. a.
GreetingService Interface b. GreetingServiceImplement class
implementing the above interface.

public interface GreetingService {


void greet(String name);
}

import org.springframework.stereotype.Service;

@Service
public class GreetingServiceImplement implements GreetingService {
@Override
public void greet(String name) {
System.out.println("Hello, " + name + "! Welcome to Spring.");
}
}

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Enable component scanning in the specified package -->


<context:component-scan base-package="your.package.name" />

</beans>

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {


public static void main(String[] args) {
// Load the Spring configuration file
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");

// Retrieve the GreetingService bean


GreetingService greetingService =
context.getBean(GreetingService.class);

// Use the GreetingService to greet a user


greetingService.greet("Alice");
}
}

OUTPUT:
Hello, Alice! Welcome to Spring.
5. Write POJO Java program to convert tightly coupled code
into loosely coupled code a. Create a parent class A with a
method display(). Create another class B that inherits class A
and contains a method display(). Create a main class to call the
display method. b. Create a class LightBulb with a method
SwitchOn(). Create another class Switch that has an object of
the LightBulb class and another method Operate(). Inside the
Operate() method call the SwitchOn() method

class A {
public void display() {
System.out.println("Display from Class A");
}
}

class B extends A {
@Override
public void display() {
System.out.println("Display from Class B");
}
}

public class Main {


public static void main(String[] args) {
B obj = new B();
obj.display();
}
}
interface Displayable {
void display();
}

class A implements Displayable {


@Override
public void display() {
System.out.println("Display from Class A");
}
}

class B implements Displayable {


@Override
public void display() {
System.out.println("Display from Class B");
}
}

public class Main {


public static void main(String[] args) {
Displayable obj = new B(); // We can change this to `new A()` without
altering the Main class
obj.display();
}
}

class LightBulb {
public void switchOn() {
System.out.println("LightBulb is switched on");
}
}

class Switch {
private LightBulb lightBulb = new LightBulb(); // Tightly coupled to
LightBulb

public void operate() {


lightBulb.switchOn();
}
}

public class Main {


public static void main(String[] args) {
Switch mySwitch = new Switch();
mySwitch.operate();
}
}

interface Switchable {
void switchOn();
}

class LightBulb implements Switchable {


@Override
public void switchOn() {
System.out.println("LightBulb is switched on");
}
}

class Switch {
private Switchable device;

// Constructor for dependency injection


public Switch(Switchable device) {
this.device = device;
}

public void operate() {


device.switchOn();
}
}

public class Main {


public static void main(String[] args) {
Switchable lightBulb = new LightBulb(); // Can change to any other
Switchable implementation
Switch mySwitch = new Switch(lightBulb); // Dependency injection
mySwitch.operate();
}
}
6. Write a simple SpringBoot Project and add the Spring Web
and Spring Boot Dev Tools dependencies. Execute the
application.

Dependencies:

● Spring Web (for building web applications and REST APIs)


● Spring Boot DevTools (for live reload and easy development)

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/api")

public class HelloController {

@GetMapping("/hello")

public String sayHello() {

return "Hello, Spring Boot!";

package com.example.springbootdemo;
import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringBootDemoApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBootDemoApplication.class, args);

OUTPUT:

Hello, Spring Boot!

7. Write a SpringBoot Program with the following: a. Create


an Employee class with two instance variables, name and age.
b. Add a parameterized constructor to set the data. c. Add an
overridden toString() method to print the details

package com.example.springbootdemo.model;

public class Employee {

private String name;

private int age;

// Parameterized constructor

public Employee(String name, int age) {


this.name = name;

this.age = age;

// Overridden toString() method

@Override

public String toString() {

return "Employee{name='" + name + "', age=" + age + "}";

// Getters (optional, for accessing fields if needed)

public String getName() {

return name;

public int getAge() {

return age;

package com.example.springbootdemo.controller;

import com.example.springbootdemo.model.Employee;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
@RestController

@RequestMapping("/api")

public class EmployeeController {

@GetMapping("/employee")

public String getEmployee() {

// Create an Employee instance using the parameterized constructor

Employee employee = new Employee("Alice Johnson", 30);

// Return the Employee details using the overridden toString() method

return employee.toString();

package com.example.springbootdemo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringBootDemoApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBootDemoApplication.class, args);

}
}

OUTPUT:

Employee{name='Alice Johnson', age=30}

8. How does Spring Boot use @ConditionalOnClass to trigger


auto-configuration?

In Spring Boot, @ConditionalOnClass is a conditional annotation that enables


or disables parts of the auto-configuration based on the presence of specific
classes on the classpath.

Purpose: @ConditionalOnClass checks if a particular class exists in the


application’s classpath before applying an auto-configuration class.

Usage: When an auto-configuration class is annotated with


@ConditionalOnClass, Spring Boot will only apply that configuration if the
specified class is present. For example, the JpaAutoConfiguration class is only
applied if the EntityManager class (part of JPA) is available on the classpath.

9. Explain the role of @ConditionalOnProperty in controlling


auto-configuration behavior.

The @ConditionalOnProperty annotation controls auto-configuration based on


specific properties in the application.properties or application.yml file.

Purpose: It enables or disables auto-configuration components based on the


presence and value of specific properties. This is useful for selectively
enabling configuration features.

Usage: You specify the property name (and optionally the value) that must be
present for the configuration to load. For example, if you want to enable a
configuration only if myapp.feature.enabled=true is set in the properties file:

@ConditionalOnProperty(name = "myapp.feature.enabled", havingValue =


"true")

public class FeatureConfiguration {


// Configuration code here

If myapp.feature.enabled is set to true, then FeatureConfiguration will be


loaded. If it’s absent or set to false, the configuration will be skipped.

10. What is the significance of @ConditionalOnBean in Spring


Boot’s auto-configuration process?

@ConditionalOnBean is used to conditionally apply configuration based on


the presence of specific beans in the Spring application context.

Purpose: It allows for conditional auto-configuration if a specific bean (or


multiple beans) is already defined in the application context.

Usage: This is useful when a configuration class depends on another bean’s


presence to function correctly. For example, if a custom configuration should
only be applied when a specific service bean exists:

@ConditionalOnBean(name = "customService")

public class CustomConfiguration {

// Configuration code here

Here, CustomConfiguration will only be applied if a bean named


customService is present in the application context. This helps avoid
configuration conflicts and allows for modular configuration based on existing
beans.

11. What is the purpose of the spring-boot-starter-parent in a


Spring Boot application, and how do we dive deeper into the
structure of any dependency used within the project?

The spring-boot-starter-parent is a special starter POM (Project Object Model)


file that serves as a default parent for Spring Boot projects. Purpose:
Centralized Dependency Management: It defines common dependencies with
predefined versions, which helps ensure version consistency across different
Spring Boot dependencies.

Default Configurations: It sets up several default configurations for Java


version, encoding, resource filtering, plugin versions, and more.

Inheritance of Properties and Plugins: By using spring-boot-starter-parent, you


inherit properties and plugins that simplify project configuration, such as
pre-configured Maven plugins.

Usage: In your pom.xml file, the spring-boot-starter-parent is typically


declared like this:

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>3.0.0</version>

</parent>

Exploring Dependency Structure:

IDE Tools: In most IDEs like IntelliJ IDEA or Eclipse, you can right-click a
dependency and select options to view its structure, transitive dependencies,
and more.

Maven Command: You can also use Maven commands to explore


dependencies. Running mvn dependency:tree in the project root lists all
dependencies in a hierarchical structure, showing the
spring-boot-starter-parent and any transitive dependencies brought in by your
project’s dependencies.
ASSIGNMENT -5 JAVA ANNOTATION

1. Create an interface ‘PaymentProcessor’ with a method


String processPayment(double amount,String currency).
Create 3 classes named creditCardProcessor,
payPalProcessor,and BankTransferProcessor each
implementing the PaymentProcessor interface. In each class,
override the processPayment method to return a string that
includes the type of paymentprocessor(eg.credit crd),the
amount, and currency. Create a class named PaymentService
that contains a dependency on the PaymentProcessor interface
and a method void makePayment(double amount, String
currency) that calls the processPayment method. The method
should print a message “processing creditcard payment of
100.0USD.

Use setter method to add dependencies. Use annotation based


configuration and create different beans to populate
PaymentProcessor with the creditCardProcessor,
PayPalProcessor, and BankTransferProcessor classes.Write a
Run class of Spring application to execute the application.

package com.example.payment;

public interface PaymentProcessor {

String processPayment(double amount, String currency);

package com.example.payment;

import org.springframework.stereotype.Component;
@Component("creditCardProcessor")

public class CreditCardProcessor implements PaymentProcessor {

@Override

public String processPayment(double amount, String currency) {

return "Processing credit card payment of " + amount + " " + currency;

@Component("payPalProcessor")

public class PayPalProcessor implements PaymentProcessor {

@Override

public String processPayment(double amount, String currency) {

return "Processing PayPal payment of " + amount + " " + currency;

@Component("bankTransferProcessor")

public class BankTransferProcessor implements PaymentProcessor {

@Override

public String processPayment(double amount, String currency) {

return "Processing bank transfer of " + amount + " " + currency;

package com.example.payment;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

public class PaymentService {

private PaymentProcessor paymentProcessor;

// Setter-based dependency injection

@Autowired

public void setPaymentProcessor(PaymentProcessor paymentProcessor) {

this.paymentProcessor = paymentProcessor;

public void makePayment(double amount, String currency) {

String result = paymentProcessor.processPayment(amount, currency);

System.out.println(result);

package com.example;

import com.example.payment.PaymentService;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication

@ComponentScan("com.example.payment")

public class PaymentApplication {

public static void main(String[] args) {

SpringApplication.run(PaymentApplication.class, args);

@Bean

CommandLineRunner runner(ApplicationContext context) {

return args -> {

PaymentService paymentService =
context.getBean(PaymentService.class);

paymentService.makePayment(100.0, "USD");

};

package com.example.payment;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Service;

@Service

public class PaymentService {

private PaymentProcessor paymentProcessor;

// Qualifier to specify the exact PaymentProcessor implementation

@Autowired

@Qualifier("creditCardProcessor")

public void setPaymentProcessor(PaymentProcessor paymentProcessor) {

this.paymentProcessor = paymentProcessor;

public void makePayment(double amount, String currency) {

String result = paymentProcessor.processPayment(amount, currency);

System.out.println(result);

2. Write a java program to create a class Book with private


data members such as bookName, authorName,and edition.
Use setter and getter, and display method. Create a annotation
based configuration and display book detail in the main class of
Spring Application.

package com.example.library;

public class Book {

private String bookName;

private String authorName;

private String edition;

// Getters and Setters

public String getBookName() {

return bookName;

public void setBookName(String bookName) {

this.bookName = bookName;

public String getAuthorName() {

return authorName;

public void setAuthorName(String authorName) {

this.authorName = authorName;

public String getEdition() {


return edition;

public void setEdition(String edition) {

this.edition = edition;

// Method to display book details

public void display() {

System.out.println("Book Name: " + bookName);

System.out.println("Author Name: " + authorName);

System.out.println("Edition: " + edition);

package com.example.library;

import org.springframework.stereotype.Component;

@Component

public class Book {

private String bookName;

private String authorName;

private String edition;

// Getters and Setters


public String getBookName() {

return bookName;

public void setBookName(String bookName) {

this.bookName = bookName;

public String getAuthorName() {

return authorName;

public void setAuthorName(String authorName) {

this.authorName = authorName;

public String getEdition() {

return edition;

public void setEdition(String edition) {

this.edition = edition;

// Method to display book details

public void display() {

System.out.println("Book Name: " + bookName);

System.out.println("Author Name: " + authorName);

System.out.println("Edition: " + edition);


}

package com.example.config;

import com.example.library.Book;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class BookConfig {

@Bean

public Book book() {

Book book = new Book();

book.setBookName("Spring in Action");

book.setAuthorName("Craig Walls");

book.setEdition("5th Edition");

return book;

package com.example;

import com.example.library.Book;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext
;

import com.example.config.BookConfig;

@SpringBootApplication

public class BookApplication implements CommandLineRunner {

public static void main(String[] args) {

SpringApplication.run(BookApplication.class, args);

@Override

public void run(String... args) throws Exception {

// Load the Spring context and get the Book bean

ApplicationContext context = new


AnnotationConfigApplicationContext(BookConfig.class);

Book book = context.getBean(Book.class);

// Display book details

book.display();

OUTPUT:
Book Name: Spring in Action

Author Name: Craig Walls

Edition: 5th Edition

3. Create class named as Student which contain a method


printMessage(String name) and it returns Hello yourname.
Create a bean object of this class and call the method
printMessage in the main class of Springboot Application by
using following ways

By implementing CommandLineRunner interface method.

Without implementing commandLineRunner.(use separate


configuration class)

package com.example.demo;

public class Student {

public String printMessage(String name) {

return "Hello, " + name;

package com.example.demo;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;
@SpringBootApplication

public class DemoApplication implements CommandLineRunner {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

// Define the Student bean

@Bean

public Student student() {

return new Student();

// Run method of CommandLineRunner interface

@Override

public void run(String... args) throws Exception {

// Retrieve the Student bean and call printMessage

Student student = student();

System.out.println(student.printMessage("John"));

package com.example.demo.config;

import com.example.demo.Student;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration

public class StudentConfig {

@Bean

public Student student() {

return new Student();

package com.example.demo;

import com.example.demo.Student;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import com.example.demo.config.StudentConfig;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

ApplicationContext context =
SpringApplication.run(DemoApplication.class, args);
// Retrieve the Student bean from the context

Student student = context.getBean(Student.class);

// Call printMessage method

System.out.println(student.printMessage("John"));

OUTPUT:

Hello, John

4. Create a constructor called MyClass which consists of


following attributes

Name, regdNo, subjectName and markSecured. Write a


display() method which displays above details.

Create 2 bean object of the constructor for two students and


call the display method in the main class of Springboot
Application by using both ways of 3.a and 3.b.

package com.example.demo;

public class MyClass {

private String name;

private String regdNo;

private String subjectName;

private int markSecured;


// Constructor

public MyClass(String name, String regdNo, String subjectName, int


markSecured) {

this.name = name;

this.regdNo = regdNo;

this.subjectName = subjectName;

this.markSecured = markSecured;

public void display() {

System.out.println("Name: " + name);

System.out.println("Registration No: " + regdNo);

System.out.println("Subject: " + subjectName);

System.out.println("Marks Secured: " + markSecured);

System.out.println();

package com.example.demo;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;
@SpringBootApplication

public class DemoApplication implements CommandLineRunner {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

// Bean definition for Student 1

@Bean

public MyClass student1() {

return new MyClass("Alice", "REG123", "Mathematics", 88);

// Bean definition for Student 2

@Bean

public MyClass student2() {

return new MyClass("Bob", "REG456", "Science", 92);

// Run method of CommandLineRunner

@Override

public void run(String... args) throws Exception {

// Retrieve each student bean and call display


MyClass student1 = student1();

MyClass student2 = student2();

student1.display();

student2.display();

package com.example.demo.config;

import com.example.demo.MyClass;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class StudentConfig {

@Bean

public MyClass student1() {

return new MyClass("Alice", "REG123", "Mathematics", 88);

@Bean

public MyClass student2() {

return new MyClass("Bob", "REG456", "Science", 92);


}

package com.example.demo;

import com.example.demo.MyClass;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import com.example.demo.config.StudentConfig;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

ApplicationContext context =
SpringApplication.run(DemoApplication.class, args);

// Retrieve each student bean from the context and call display

MyClass student1 = context.getBean("student1", MyClass.class);

MyClass student2 = context.getBean("student2", MyClass.class);

student1.display();

student2.display();

}
OUTPUT:

Name: Alice

Registration No: REG123

Subject: Mathematics

Marks Secured: 88

Name: Bob

Registration No: REG456

Subject: Science

Marks Secured: 92

5. Create a package of 4 classes named as address, Teacher,


app, javaConfig.

Address has fields as houseNo, city, postOffice, pin, state. Use


setter method for the given fields and toString method to print
string representation of the object.

Teacher class has name, id, mobileNo, and address fields. Use
the setter method and toString method for this class.
javaConfig class is java annotation-based configuration file
which creates two address beans and on teacher bean and
initialize the fields of both classes. In teacher class use any one
address by using @Qualifier annotation.

Call the teacher object in app class which consists of main


method of Spring application.

package com.example.demo;
public class Address {

private String houseNo;

private String city;

private String postOffice;

private String pin;

private String state;

// Setter methods

public void setHouseNo(String houseNo) {

this.houseNo = houseNo;

public void setCity(String city) {

this.city = city;

public void setPostOffice(String postOffice) {

this.postOffice = postOffice;

public void setPin(String pin) {

this.pin = pin;

public void setState(String state) {

this.state = state;

}
// toString method for displaying Address details

@Override

public String toString() {

return "Address{" +

"houseNo='" + houseNo + '\'' +

", city='" + city + '\'' +

", postOffice='" + postOffice + '\'' +

", pin='" + pin + '\'' +

", state='" + state + '\'' +

'}';

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

public class Teacher {

private String name;

private int id;

private String mobileNo;

@Autowired

@Qualifier("address1") // Specify which Address bean to use


private Address address;

// Setter methods

public void setName(String name) {

this.name = name;

public void setId(int id) {

this.id = id;

public void setMobileNo(String mobileNo) {

this.mobileNo = mobileNo;

public void setAddress(Address address) {

this.address = address;

// toString method for displaying Teacher details

@Override

public String toString() {

return "Teacher{" +

"name='" + name + '\'' +

", id=" + id +

", mobileNo='" + mobileNo + '\'' +

", address=" + address +


'}';

package com.example.demo.config;

import com.example.demo.Address;

import com.example.demo.Teacher;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class javaConfig {

@Bean

public Address address1() {

Address address = new Address();

address.setHouseNo("101");

address.setCity("New York");

address.setPostOffice("NYPO");

address.setPin("10001");

address.setState("NY");

return address;

}
@Bean

public Address address2() {

Address address = new Address();

address.setHouseNo("202");

address.setCity("Los Angeles");

address.setPostOffice("LAPO");

address.setPin("90001");

address.setState("CA");

return address;

@Bean

public Teacher teacher() {

Teacher teacher = new Teacher();

teacher.setName("John Doe");

teacher.setId(101);

teacher.setMobileNo("123-456-7890");

return teacher;

package com.example.demo;
import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import com.example.demo.config.javaConfig;

@SpringBootApplication

public class App {

public static void main(String[] args) {

ApplicationContext context = SpringApplication.run(App.class, args);

// Retrieve the Teacher bean and display its details

Teacher teacher = context.getBean(Teacher.class);

System.out.println(teacher);

OUTPUT:

Teacher{name='John Doe', id=101, mobileNo='123-456-7890',


address=Address{houseNo='101', city='New York', postOffice='NYPO',
pin='10001', state='NY'}}

6. Create a customer class which consists of customerName,


accountNo, IFSCCode, use setter method and override the
toString Method.

Create a configuration class(annotation based) named as


conFig. Use configuration and componntscan Annotatuion and
create a bean for customer class and initialize the field by
calling setter method of customer class. Display details of
customer in the app/run class which consists of main method of
SpringApplication.

package com.example.demo;

public class Customer {

private String customerName;

private String accountNo;

private String IFSCCode;

// Setter methods

public void setCustomerName(String customerName) {

this.customerName = customerName;

public void setAccountNo(String accountNo) {

this.accountNo = accountNo;

public void setIFSCCode(String IFSCCode) {

this.IFSCCode = IFSCCode;

// toString method for displaying Customer details

@Override

public String toString() {

return "Customer{" +
"customerName='" + customerName + '\'' +

", accountNo='" + accountNo + '\'' +

", IFSCCode='" + IFSCCode + '\'' +

'}';

package com.example.demo.config;

import com.example.demo.Customer;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

@Configuration

@ComponentScan(basePackages = "com.example.demo")

public class conFig {

@Bean

public Customer customer() {

Customer customer = new Customer();

customer.setCustomerName("Alice Johnson");

customer.setAccountNo("1234567890");

customer.setIFSCCode("ABCD0123456");

return customer;

}
}

package com.example.demo;

import com.example.demo.config.conFig;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

@SpringBootApplication

public class App {

public static void main(String[] args) {

ApplicationContext context = SpringApplication.run(App.class, args);

// Retrieve the Customer bean and display its details

Customer customer = context.getBean(Customer.class);

System.out.println(customer);

OUTPUT:

Customer{customerName='Alice Johnson', accountNo='1234567890',


IFSCCode='ABCD0123456'}

7. Create a class named as Book having fields title, price,


pDate(reference of class pubDate) and override the toString
Method. Use @value ,@Autowire @Component and @override
annotation in appropriate position. The class pubDate consists
of filed day, month, and year. Use @value to give value of each
field and write toString method. Display book details in the
main method of app.java of Spring Application.

package com.example.demo;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

@Component

public class PubDate {

@Value("12")

private int day;

@Value("05")

private int month;

@Value("2021")

private int year;

// toString method for displaying PubDate details

@Override

public String toString() {

return "PubDate{" +

"day=" + day +

", month=" + month +

", year=" + year +

'}';
}

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

@Component

public class Book {

@Value("Spring in Action")

private String title;

@Value("45.99")

private double price;

@Autowired

private PubDate pDate;

// toString method for displaying Book details

@Override

public String toString() {

return "Book{" +

"title='" + title + '\'' +

", price=" + price +

", pDate=" + pDate +

'}';
}

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

@SpringBootApplication

public class App {

public static void main(String[] args) {

ApplicationContext context = SpringApplication.run(App.class, args);

// Retrieve the Book bean and display its details

Book book = context.getBean(Book.class);

System.out.println(book);

OUTPUT:

Book{title='Spring in Action', price=45.99, pDate=PubDate{day=12,


month=05, year=2021}}

8. Create a class and use appropriate annotation to display


your name in browser when user type.localhost:8080/home.

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;
@RestController

public class HomeController {

@GetMapping("/home")

public String displayName() {

return "Hello, my name is SOA!";

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

OUTPUT:

Hello, my name is SOA!

You might also like