0% found this document useful (0 votes)
12 views11 pages

Adp Ass 4

Uploaded by

prattyush49.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views11 pages

Adp Ass 4

Uploaded by

prattyush49.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

ADP Assignment 4

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

Answer :-
1. PaymentMethod Interface

public interface PaymentMethod {


void processPayment(double amount);
}

2. CreditCard Class

public class CreditCard implements PaymentMethod {


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

3. PayPal Class

public class PayPal implements PaymentMethod {


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

4. ShoppingCart Class
public class ShoppingCart {
private PaymentMethod paymentMethod;
public ShoppingCart(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
} public void checkout(double amount) {
paymentMethod.processPayment(amount);
}}
5. App Class (to run the application)

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

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

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

// Perform checkout
cart.checkout(250.0);
}
}

6. Spring XML Configuration (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">
<bean id="creditCard" class="CreditCard"/>
<bean id="payPal" class="PayPal"/>

<!-- Inject PaymentMethod into ShoppingCart -->


<bean id="shoppingCart" class="ShoppingCart">
<constructor-arg ref="creditCard"/> <!-- Use CreditCard for payment -->
</bean>

</beans>

Output :-
Payment of $250.0 processed through Credit Card.
<constructor-arg ref="payPal"/>
Payment of $250.0 processed through PayPal.

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

Answer :-
1. Define the EmailService Class

public class EmailService {


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

public class SMSService {


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

3. Define the NotificationService Class


public class NotificationService {

private EmailService emailService;


private SMSService smsService;
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
public void setSmsService(SMSService smsService) {
this.smsService = smsService;
}
public void notifyByEmail(String msg) {
emailService.sendEmail(msg);
}

public void notifyBySMS(String msg) {


smsService.sendSMS(msg);
}
}

4. Spring XML Configuration (applicationContext.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="EmailService"/>
<bean id="smsService" class="SMSService"/>
<bean id="notificationService" class="NotificationService">
<property name="emailService" ref="emailService"/>
<property name="smsService" ref="smsService"/>
</bean>
</beans>

5. the App Class to Run the Application


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
NotificationService notificationService = (NotificationService) context.getBean("notificationService");
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.

Answer –
1. Create the UserRepository Class

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {

public void saveUser() {


System.out.println("User has been saved to the repository.");
}
}

2. Create the UserService Class


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

@Service
public class UserService {

private UserRepository userRepository;


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

public void registerUser() {


userRepository.saveUser();
}
}

3. Create the Configuration Class

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "your.package.name")
public class AppConfig {

}
4. Define the App Class

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {


public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);

// Use the service to register a user


userService.registerUser();
}
}

Output :-
User has been saved to the repository.

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

Answer :-
Step 1: Define the GreetingService Interface

public interface GreetingService {


void sayGreeting();
}

Step 2: Implement the GreetingServiceImplement Class

import org.springframework.stereotype.Service;

@Service
public class GreetingServiceImplement implements GreetingService {

@Override
public void sayGreeting() {
System.out.println("Hello, Welcome to Spring using component-scan and annotations!");
}
}

Step 3: Create the App Class to Run the Application


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

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
GreetingService greetingService = context.getBean(GreetingService.class);

// Call the greeting method


greetingService.sayGreeting();
}
}

Output :-
Hello, Welcome to Spring using component-scan and annotations!

5. Write POJO Java program to convert tightly coupled code into loosely coupled code
[1] 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.
[2] 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

Answer –
Part 1: Convert Tightly Coupled Code into Loosely Coupled Code
Tightly Coupled Code (Inheritance)
class A {
public void display() {
System.out.println("Display method in class A");
}
}
class B extends A {
@Override
public void display() {
System.out.println("Display method in class B");
}
}
public class MainTightlyCoupled {
public static void main(String[] args) {
B obj = new B(); // Tightly coupled
obj.display(); // This will call the display method in class B
}
}

Output :-
Display method in class B
Loosely Coupled Code (Using Interfaces)
interface Displayable {
void display();
}
class A implements Displayable {
@Override
public void display() {
System.out.println("Display method in class A");
}
}
class B implements Displayable {
@Override
public void display() {
System.out.println("Display method in class B");
}
}
public class MainLooselyCoupled {
public static void main(String[] args) {
Displayable obj = new B();
obj.display();
}
}

Output :-
Display method in class B

Part 2: LightBulb and Switch Example


Tightly Coupled Code
class LightBulb {
public void switchOn() {
System.out.println("LightBulb is switched on");
}
}
class Switch {
private LightBulb lightBulb = new LightBulb();

public void operate() {


lightBulb.switchOn();
}
}

// Main class to run the program


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

Output :- LightBulb is switched on


Loosely Coupled Code (Using Interfaces)
interface LightSource {
void switchOn();
}
class LightBulb implements LightSource {
@Override
public void switchOn() {
System.out.println("LightBulb is switched on");
}
}
class Switch {
private LightSource lightSource;
public Switch(LightSource lightSource) {
this.lightSource = lightSource;
}

public void operate() {


lightSource.switchOn();
}
}
public class MainLooselyCoupledSwitch {
public static void main(String[] args) {
LightSource bulb = new LightBulb();
Switch mySwitch = new Switch(bulb);
mySwitch.operate();
}
}

Output :-
LightBulb is switched on

6. Write a simple SpringBoot Project and add the Spring Web and Spring Boot Dev Tools
dependencies. Execute the application.
Answer –
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Write the Controller Class
package com.example.demo;

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

@RestController
public class GreetingController {

@GetMapping("/greet")
public String greet() {
return "Hello, Welcome to Spring Boot!";
}
}

Main Application Class


package com.example.demo;

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, Welcome to 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

Answer –
Create the Employee Class
package com.example.demo;
public class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Employee [Name: " + name + ", Age: " + age + "]";
}
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;
}
}

Create a REST Controller to Test the Employee Class

package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {

@GetMapping("/employee")
public String getEmployee() {
Employee emp = new Employee("John Doe", 30);
return emp.toString();
}
}

Main Application Class

package com.example.demo;

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: John Doe, Age: 30]
8. How does Spring Boot use @ConditionalOnClass to trigger auto-configuration?

Answer –
In Spring Boot, auto-configuration is a powerful feature that configures application beans and settings
based on classpath content and other environment settings. This is usually done to reduce the need for
manual configuration of beans and services.
One key annotation used for this purpose is @ConditionalOnClass, which allows certain auto-
configuration classes to be loaded only if specific classes are present on the classpath.

a. Auto-Configuration Class: Spring Boot defines many auto-configuration classes, each


designed to configure a specific service or component (such as a data source, web server, or
messaging queue). These classes use @ConditionalOnClass to ensure they are only loaded if the
relevant dependencies are available.
b. Classpath Check: At startup, Spring Boot scans the classpath to check if the classes specified
in the @ConditionalOnClass annotation are available. If they are present, the associated
configuration is applied.
c. Trigger Auto-Configuration: If the required class is found, the beans defined in the auto-
configuration class are loaded into the Spring application context. Otherwise, the configuration
is skipped.

9. Explain the role of @ConditionalOnProperty in controlling auto-configuration behavior.

Answer –
In Spring Boot, auto-configuration can be controlled based on various conditions, including the
presence of certain properties. The annotation @ConditionalOnProperty is used to enable or disable
auto-configuration or beans based on the presence and value of specific properties in the application's
configuration files (like application.properties or application.yml).

10. What is the significance of @ConditionalOnBean in Spring Boot’s auto-configuration process?

Answer –
In Spring Boot, auto-configuration allows for the automatic configuration of beans based on certain
conditions, such as the presence of classes, properties, or other beans in the application context. One of
the key annotations used in this process is @ConditionalOnBean, which controls auto-configuration or
bean creation based on the presence of specific beans in the Spring context.

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?

Answer –
The spring-boot-starter-parent is a parent POM (Project Object Model) in Maven that provides default
configurations and dependency management for Spring Boot projects. It simplifies the setup and
configuration of Spring Boot applications by offering default versions of libraries, plugins, and settings,
enabling developers to focus on application development rather than boilerplate configuration.

You might also like