0% found this document useful (0 votes)
15 views12 pages

Assignment 4 Debi

Uploaded by

devildada0987
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)
15 views12 pages

Assignment 4 Debi

Uploaded by

devildada0987
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/ 12

Assignment - IV

Topic: SpringBoot Starter, SpringBoot Starter


Dependencies and Auto Configuration, Annotation-Based
Java Configuration, Xml-Based Configuration, Loosely
Coupled Dependency Injection
Name: Debi Prasad Rath
Registration Number: 2251018009
Section: I

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
CODE:
PaymentMethod.java
package com.A4Q1;

public interface PaymentMethod {


public void processPayment(double amount);
}

CreditCard.java
package com.A4Q1;

public class CreditCard implements PaymentMethod{


@Override
public void processPayment(double amount) {
System.out.println("Payment processed with Credit Card. Amount: "+amount);
}
}

PayPal.java
package com.A4Q1;
public class PayPal implements PaymentMethod{
@Override
public void processPayment(double amount){
System.out.println("Payment processed with PayPal. Amount: "+amount);
}
}

ShoppingCart.java
package com.A4Q1;
public class ShoppingCart {
PaymentMethod paymentMethod;
public ShoppingCart(PaymentMethod paymentMethod){
this.paymentMethod=paymentMethod;
}

public void checkOut(double amount){


System.out.println("Checkout started...");
paymentMethod.processPayment(amount);
System.out.println("Checkout completed !");
}
}

App.java
package com.A4Q1;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class App {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("bean3.xml");
ShoppingCart sc = (ShoppingCart) context.getBean("ShoppingCart");
sc.checkOut(500.00);
}
}
OUTPUT:

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

CODE:
EmailService.java
package com.A4Q2;

public class EmailService {


public void sendEmail(String msg){
System.out.println("Message sent via Email");
System.out.println(msg);
}
}

SMSService.java
package com.A4Q2;

public class SMSService {


public void sendSMS(String msg){
System.out.println("Message sent via SMS");
System.out.println(msg);
}
}

NotificationService.java
package com.A4Q2;

public class NotificationService {


EmailService emailService;
SMSService smsService;

public void setEmailService(EmailService emailService) {


this.emailService = emailService;
}

public void setSmsService(SMSService smsService) {


this.smsService = smsService;
}

void notifyByMail(String msg){


emailService.sendEmail(msg);
}

void notifyBySMS(String msg){


smsService.sendSMS(msg);
}
}

App.java
package com.A4Q2;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
NotificationService ns=(NotificationService) context.getBean("NotificationService");
ns.notifyByMail("Hey, This is an Email.");
ns.notifyBySMS("Hey, This is a SMS.");
}
}
OUTPUT:

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.

CODE:
UserRepository.java
package com.A4Q3;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
void saverUser(){
System.out.println("User data saved");
}
}

UserService.java
package com.A4Q3;

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

@Service
public class UserService {
UserRepository userRepository;

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

void registerUser(){
System.out.println("User registered");
}
}

AppConfig.java
package com.A4Q3;

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

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

App.java
package com.A4Q3;

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);


userService.registerUser();
}
}
OUTPUT:

4. Write a Java Program to demonstrate a simple example using


<context:component-scan> with annotation-based configuration in
Spring.
a. GreetingService Interface
b. GreetingServiceImplement class implementing the above interface

CODE:
GreetingService.java
package com.A4Q4;

public interface GreetingService {


void greet();
}

GreetingServiceImplement.java
package com.A4Q4;

import org.springframework.stereotype.Service;

@Service
public class GreetingServiceImplement implements GreetingService{
@Override
public void greet() {
System.out.println("Hello, welcome to Spring with <context:component-scan>!");
}
}
bean,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"
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
https://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.A4Q4" />


</beans>

App.java
package com.A4Q4;

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

public class App {


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

OUTPUT:

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

CODE:
Displayable.java

package com.A4Q5A;

public interface Displayable {


void display();
}
A.java
package com.A4Q5A;

public class A implements Displayable{


@Override
public void display() {
System.out.println("You are in class A");
}
}

B.java
package com.A4Q5A;

public class B implements Displayable{


@Override
public void display() {
System.out.println("You are in class B");
}
}

App.java

package com.A4Q5A;

public class App {


public static void main(String[] args) {
Displayable displayA=new A();
Displayable displayB=new B();

displayA.display();
displayB.display();
}
}

OUTPUT:

Switchable.java
package com.A4Q5B;

public interface Switchable {


void switchOn();
}

LightBulb.java
package com.A4Q5B;

public class LightBulb implements Switchable{


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

Switch.java
package com.A4Q5B;

public class Switch {


private Switchable device;

public Switch(Switchable device) {


this.device = device;
}

public void operate() {


device.switchOn();
}
}

App.java
package com.A4Q5B;

public class App {


public static void main(String[] args) {
Switchable lightBulb = new LightBulb();
Switch lightSwitch = new Switch(lightBulb);

lightSwitch.operate();
}
}

OUTPUT:

6. Write a simple SpringBoot Project and add the Spring Web and
Spring Boot Dev Tools dependencies. Execute the application.

Code:
HelloSpring.java
package com.A4Q6;

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

@RestController
public class HelloSpring {
@GetMapping("/hello")
public String message(){
return "Hello Spring Devs";
}
}

App.java
package com.A4Q6;

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

@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

OUTPUT:

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.

CODE:
Employee.java
package com.A4Q7;

public class Employee {


String name;
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 int getAge() {


return age;
}
}

EmployeeController.java
package com.A4Q7;

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

@RestController
public class EmployeeController {
@GetMapping("/employee")
public String getEmployee() {
Employee employee = new Employee("XYZ", 25);
return employee.toString();
}
}

OUTPUT:

8. How does Spring Boot use @ConditionalOnClass to trigger auto-configuration?

Answer:

 @ConditionalOnClass tells Spring Boot to enable auto-configuration only if a specific class is on


the classpath.
 Example: If we use @ConditionalOnClass(DataSource.class), Spring Boot will configure database
settings only if DataSource is available in the project.
9. Explain the role of @ConditionalOnProperty in controlling auto-configuration
behavior.
Answer:

 @ConditionalOnProperty lets us enable or disable auto-configuration based on properties.


 Example: @ConditionalOnProperty(name = "featureX.enabled", havingValue = "true") will only
activate the configuration if featureX.enabled is set to true in application properties.

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


configuration process?

Answer:

 @ConditionalOnBean enables auto-configuration if a specific bean exists in the application


context.
 Example: @ConditionalOnBean(name = "myBean") will only configure settings if myBean is
already defined in the project.

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:

 spring-boot-starter-parent provides default configurations and dependency versions for Spring


Boot projects, making setup easier.
 To check a dependency’s structure, we can use the command: mvn dependency:tree (for Maven
projects) to view all dependencies and their hierarchy.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy