0% found this document useful (0 votes)
10 views24 pages

1 Write A Spring Program For Dependency Injection by Using Constructor With Tag. Slip 1

Uploaded by

pmovies347
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)
10 views24 pages

1 Write A Spring Program For Dependency Injection by Using Constructor With Tag. Slip 1

Uploaded by

pmovies347
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/ 24

1 Write a spring program for dependency injection by using

constructor with <constructor-arg> tag. Slip 1


Employee.java
public class Employee {
private String name;
private Address address;
// Constructor
public Employee(String name, Address address) {
this.name = name;
this.address = address;
}
// Getters
public String getName() {
return name;
}
public Address getAddress() {
return address;
}
}
Address.java
public class Address {
private String street;
private String city;
// Constructor
public Address(String street, String city) {
this.street = street;
this.city = city;
}
// Getters
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
}
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/bea
ns
http://www.springframework.org/schema/beans/spring-
beans.xsd">
<!-- Define Address bean -->
<bean id="address" class="com.example.Address">
<constructor-arg name="street" value="123 Main St"/>
<constructor-arg name="city" value="Anytown"/>
</bean>
<!-- Define Employee bean with dependency on Address -->
<bean id="employee" class="com.example.Employee">
<constructor-arg name="name" value="John Doe"/>
<constructor-arg name="address" ref="address"/>
</bean> >> </beans>
Main.java import org.springframework.context.ApplicationContext;
import.org.springframework.context.support.ClassPathXmlApplicatio
nContext;
public class Main { >> public static void main(String[] args) {
// Create application context
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
// Get Employee bean
Employee employee = (Employee) context.getBean("employee");
// Print employee details
System.out.println("Name: " + employee.getName());
System.out.println("Address: " +
employee.getAddress().getStreet() + ", " +
employee.getAddress().getCity()); >> } >> }

Output: Name: John Doe


Address: 123 Main St, Anytown
2 Write a spring program for object coupling problem using tight
coupling.
Employee.java
public class Employee {
private String name;
private Address address;
// Tight Coupling: Employee is tightly coupled with OfficeAddress
public Employee(String name) {
this.name = name; >> this.address = new OfficeAddress();
} >> // Getters
public String getName() {
return name; >> }
public Address getAddress() {
return address; >> } >> }
Address.java
public interface Address {
String getStreet();
String getCity(); >> }
OfficeAddress.java
public class OfficeAddress implements Address {
@Override
public String getStreet() {
return "123 Office St"; >> }
@Override
public String getCity() {
return "Office City"; >> } >> }
HomeAddress.java
public class HomeAddress implements Address {
@Override
public String getStreet() {
return "456 Home St"; >> }
@Override >> public String getCity() {
return "Home City"; >> } >> }
Main.java
public class Main {
public static void main(String[] args) {
// Create Employee object
Employee employee = new Employee("John Doe");
// Print employee details
System.out.println("Name: " + employee.getName());
System.out.println("Address: " +
employee.getAddress().getStreet() + ", " +
employee.getAddress().getCity());
}
}
Output:
Name: John Doe
Address: 123 Office St, Office City
3 Write a java program to implement bean life cycle by using xml.
Employee.java
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Employee implements BeanNameAware, InitializingBean,
DisposableBean {
private String name;
private String address;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address; >> }
public void setAddress(String address) {
this.address = address; >> }
// BeanNameAware methods
@Override
public void setBeanName(String beanName) {
System.out.println("Bean name: " + beanName);
}
// InitializingBean methods
@Override
public void afterPropertiesSet() {
System.out.println("Properties set");
}
// DisposableBean methods
@Override
public void destroy() {
System.out.println("Bean destroyed");
}
}
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/bea
ns
http://www.springframework.org/schema/beans/spring-
beans.xsd">
<!-- Define Employee bean -->
<bean id="employee" class="com.example.Employee">
<property name="name" value="John Doe"/>
<property name="address" value="123 Main St"/>
</bean>
</beans>
Main.java
import org.springframework.context.ApplicationContext;
import.org.springframework.context.support.ClassPathXmlApplicatio
nContext;
public class Main {
public static void main(String[] args) {
// Create application context
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
// Get Employee bean
Employee employee = (Employee) context.getBean("employee");
// Print employee details
System.out.println("Name: " + employee.getName());
System.out.println("Address: " + employee.getAddress());
// Close application context
((ClassPathXmlApplicationContext) context).close();
}
}
Output:
Bean name: employee
Properties set
Name: John Doe
Address: 123 Main St
Bean destroyed
4 Write a java program for bean scope using prototype.
Employee.java
import org.springframework.stereotype.Component;
@Component
public class Employee {
private String name;
private String address;
public Employee() {
System.out.println("Employee constructor called");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
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/bea
ns
http://www.springframework.org/schema/beans/spring-
beans.xsd">
<!-- Define Employee bean with prototype scope -->
<bean id="employee" class="com.example.Employee"
scope="prototype">
<property name="name" value="John Doe"/>
<property name="address" value="123 Main St"/>
</bean>
</beans>
Main.java
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;
public class Main {
public static void main(String[] args) {
// Create application context
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
// Get Employee bean
Employee employee1 = (Employee)
context.getBean("employee");
Employee employee2 = (Employee)
context.getBean("employee");
// Print employee details
System.out.println("Employee 1: " + employee1.getName() + ", "
+ employee1.getAddress());
System.out.println("Employee 2: " + employee2.getName() + ", "
+ employee2.getAddress());
// Check if employee1 and employee2 are the same instance
System.out.println("Are employee1 and employee2 the same
instance? " + (employee1 == employee2));
}
}
Output:
Employee constructor called
Employee constructor called
Employee 1: John Doe, 123 Main St
Employee 2: John Doe, 123 Main St
Are employee1 and employee2 the same instance? false
1 Write a spring program for @Qualifier annotation.
Employee.java
public class Employee {
private String name;
private Address address;
// Constructor
public Employee(String name, Address address) {
this.name = name;
this.address = address;
}
// Getters
public String getName() {
return name;
}
public Address getAddress() {
return address;
}
}
Address.java
public interface Address {
String getStreet();
String getCity();
}
OfficeAddress.java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Qualifier;
@Component >> @Qualifier("officeAddress")
public class OfficeAddress implements Address {
@Override >> public String getStreet() {
return "123 Office St"; >> }
@Override >> public String getCity() {
return "Office City"; >> } >> }
HomeAddress.java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Qualifier;
@Component
@Qualifier("homeAddress")
public class HomeAddress implements Address {
@Override
public String getStreet() {
return "456 Home St";
}
@Override >> public String getCity() {
return "Home City"; >> } >> }
EmployeeConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration >> public class EmployeeConfig {
@Bean
public Employee employee(@Qualifier("officeAddress") Address
address) {
return new Employee("John Doe", address); >> } >> }
Main.java
import org.springframework.context.ApplicationContext;
import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(EmployeeConfig.class);
Employee employee = (Employee) context.getBean("employee");
System.out.println("Name: " + employee.getName());
System.out.println("Address: " +
employee.getAddress().getStreet() + ", " +
employee.getAddress().getCity());
}
}
Output:
Name: John Doe
Address: 123 Office St, Office City
2 Write a spring program for stereotype annotation by using
@Component annotation and @Value annotation.
Employee.java
Java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Employee {
@Value("John Doe")
private String name;

@Value("123 Main St")


private String address;

// Getters
public String getName() {
return name;
}

public String getAddress() {


return address;
}
}
Main.java
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicatio
nContext;

public class Main {


public static void main(String[] args) {
// Create application context
ApplicationContext context = new
AnnotationConfigApplicationContext("com.example");

// Get Employee bean


Employee employee = (Employee) context.getBean("employee");

// Print employee details


System.out.println("Name: " + employee.getName());
System.out.println("Address: " + employee.getAddress());
}
}
Output:
Name: John Doe
Address: 123 Main St
3 Write a spring MVC program and display the message in the JSP
page
HelloController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String hello(Model model) {
String message = helloService.getMessage();
model.addAttribute("message", message);
return "hello";
}
}
HelloService.java
import org.springframework.stereotype.Service;
@Service
public class HelloService {
public String getMessage() {
return "Hello, World!";
}
}
dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/bea
ns
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context.xsd">
<!-- Enable MVC annotation support -->
<mvc:annotation-driven/>
<!-- Define view resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewR
esolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Define controller package -->
<context:component-scan base-package="com.example"/>
</beans>
hello.jsp
Jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"
%>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
Deployment
Build the project using Maven or Gradle.
Deploy the WAR file to a servlet container like Apache Tomcat.
Access the application at http://localhost:8080/hello.

Output:-
The application will display the message "Hello, World!" on the
hello.jsp page.
4 Write a spring MVC program for exception handling.
ExceptionHandler.java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice >> public class ExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView
handleUserNotFoundException(UserNotFoundException exception) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMessage",
exception.getMessage());
return modelAndView; > } > @ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handleException(Exception exception) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMessage", "An unexpected
error occurred");
return modelAndView; >> } >> }
UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller >> public class UserController {
@Autowired >> private UserService userService;
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id, Model model) {
try { >> User user = userService.getUser(id);
model.addAttribute("user", user); >> return "user";
} catch (UserNotFoundException exception) {
throw exception; >> } >> } >> }
UserService.java import org.springframework.stereotype.Service;
@Service >> public class UserService {
public User getUser(Long id) throws UserNotFoundException {
// Simulate a database query >> if (id == 1) {
return new User(id, "John Doe"); >> } else {
throw new UserNotFoundException("User not found with id " + id);
} >> } >> }
UserNotFoundException.java public class UserNotFoundException
extends Exception {
public UserNotFoundException(String message) {
super(message); >> } >> }
dispatcher-servlet.xml >> 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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/bea
ns
http://www.springframework.org/schema/beans/spring-
beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-
mvc.xsd">
<!-- Enable MVC annotation support -->
<mvc:annotation-driven/>
<!-- Define view resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewR
esolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean> >> <!-- Define exception handler -->
<bean id="exceptionHandler"
class="com.example.ExceptionHandler"/>
</beans> >> error.jsp >> Jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"
%> >> <html> >> <head> >> <title>Error Page</title>
</head> >> <body> >> <h1>Error</h1>
<p>${errorMessage}</p> >> </body> >></html>

You might also like