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

ADPJ4

Uploaded by

jenasubhradeep
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)
37 views11 pages

ADPJ4

Uploaded by

jenasubhradeep
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

Department of Computer Science & Engineering

Faculty of Engineering and Technology (ITER)

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 use the PaymentMethod instance to process payments
e. App Class to run the application
Ans:
[Link]
public interface PaymentMethod {
void processPayment(double amount);
}

[Link]
public class CreditCard implements PaymentMethod {
@Override
public void processPayment(double amount) {
[Link]("Processing credit card payment of $" + amount);
}
}

[Link]
public class PayPal implements PaymentMethod {
@Override
public void processPayment(double amount) {
[Link]("Processing PayPal payment of $" + amount);
}
}

[Link]
public class ShoppingCart {
private PaymentMethod paymentMethod;
public ShoppingCart(PaymentMethod paymentMethod) {
[Link] = paymentMethod;
}
public void checkout(double amount) {
[Link](amount);
}
}

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

[Link]
import [Link];
import [Link];

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");
ShoppingCart cart = (ShoppingCart) [Link]("shoppingCart");
[Link](250.0);
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

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


<bean id="payPal" class="PayPal"/>
<bean id="shoppingCart" class="ShoppingCart">
<constructor-arg ref="creditCard"/>
</bean>
</beans>

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
Ans:
[Link]
public class EmailService {
public void sendEmail(String msg) {
[Link]("Email sent with message: " + msg);
}
}

[Link]
public class SMSService {
public void sendSMS(String msg) {
[Link]("SMS sent with message: " + msg);
}
}

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

[Link]
public class NotificationService {
private EmailService emailService;
private SMSService smsService;

public void setEmailService(EmailService emailService) {


[Link] = emailService;
}
public void setSmsService(SMSService smsService) {
[Link] = smsService;
}
public void notifyByEmail(String msg) {
[Link](msg);
}
public void notifyBySMS(String msg) {
[Link](msg);
}
}

[Link]
import [Link];
import [Link];

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");
NotificationService notificationService=(NotificationService) [Link]("notificationService");
[Link]("Hello via Email!");
[Link]("Hello via SMS!");
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

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

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

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.

Ans:
[Link]
import [Link];

@Repository
public class UserRepository {

public void saveUser() {


[Link]("User has been saved to the repository.");
}
}

[Link]
import [Link];
import [Link];

@Service
public class UserService {

private UserRepository userRepository;

@Autowired
public void setUserRepository(UserRepository userRepository) {
[Link] = userRepository;
}

public void registerUser() {


[Link]();
}
}

[Link]
import [Link];
import [Link];

@Configuration

@ComponentScan(basePackages = "[Link]")
public class AppConfig {
}

[Link]
import [Link];

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

import [Link];

public class App {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
UserService userService = [Link]([Link]);
[Link]();
}
}

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
Ans:
[Link]
public interface GreetingService {
void sayGreeting();
}

[Link]
import [Link];

@Service
public class GreetingServiceImplement implements GreetingService {
@Override
public void sayGreeting() {
[Link]("Hello, Welcome to Spring using component-scan and
annotations!");
}
}

[Link]
import [Link];
import [Link];

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext ("[Link]");
GreetingService greetingService = [Link]([Link]);
[Link]();
}
}

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<context:component-scan base-package="[Link]"/>

</beans>

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
Ans:
Part 1: Convert Tightly Coupled Code into Loosely Coupled Code

Tightly Coupled Code (Inheritance)

class A {
public void display() {
[Link]("Display method in class A");
}
}
class B extends A {
@Override

public void display() {


[Link]("Display method in class B");
}
}

public class MainTightlyCoupled {


public static void main(String[] args) {

B obj = new B(); // Tightly coupled


[Link](); // This will call the display method in class B
}
}

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

Loosely Coupled Code (Using Interfaces)


interface Displayable {
void display();
}

class A implements Displayable {


@Override
public void display() {
[Link]("Display method in class A");
}
}

class B implements Displayable {


@Override
public void display() {
[Link]("Display method in class B");
}
}

public class MainLooselyCoupled {


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

Part 2: LightBulb and Switch Example


Tightly Coupled Code
class LightBulb {
public void switchOn() {
[Link]("LightBulb is switched on");
}
}

class Switch {
private LightBulb lightBulb = new LightBulb();

public void operate() {


[Link]();
}
}

public class MainTightlyCoupledSwitch {


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

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

Loosely Coupled Code (Using Interfaces)


class LightBulb {
public void switchOn() {
[Link]("LightBulb is switched on");
}
}
class Switch {
private LightBulb lightBulb = new LightBulb();

public void operate() {


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

6. Write a simple SpringBoot Project and add the Spring Web and Spring Boot Dev
Tools dependencies.
Execute the application.
Ans:
[Link]
package [Link];
import [Link];
import [Link];

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

[Link]
package [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

[Link]
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

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
Ans:
[Link]
package [Link];
public class Employee {
private String name;
private int age;
public Employee(String name, int age) {
[Link] = name;
[Link] = age;
}
@Override
public String toString() {
return "Employee [Name: " + name + ", Age: " + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

[Link] = age;
}
}

[Link]
package [Link];
import [Link];
import [Link];

@RestController
public class EmployeeController {
@GetMapping("/employee")
public String getEmployee() {
Employee emp = new Employee("John Doe", 30);
return [Link]();
}
}
[Link]
package [Link];
import [Link];
import [Link];

@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

[Link]
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Name:_____________________ Regd. Number:_____________________


Department of Computer Science & Engineering
Faculty of Engineering and Technology (ITER)

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


Ans:
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
Ans:
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 [Link] or [Link]).

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


configuration process?
Ans:
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?
Ans:
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.

Name:_____________________ Regd. Number:_____________________

You might also like