0% found this document useful (0 votes)
9 views18 pages

Q.4. Write A Spring Program For Bean Definition Inheritance by Using Constructor

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)
9 views18 pages

Q.4. Write A Spring Program For Bean Definition Inheritance by Using Constructor

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

Q.4.

Write a spring program for bean definition inheritance by using


constructor.
pom.xml.
<dependencies> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Or the latest version -->
</dependency> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.24</version> <!-- Or the latest version -->
</dependency> >> </dependencies>
Person.java (Parent Bean)
public class Person { >> private String name;
private int age; >> // Constructor
public Person(String name, int age) { >> this.name = name;
this.age = age; >> } >> // 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; >> }
@Override >> public String toString() {
return "Person{name='" + name + "', age=" + age + "}"; >> } >> }
Employee.java (Child Bean 1)
public class Employee extends Person { >> private String position;
// Constructor
public Employee(String name, int age, String position) {
super(name, age); // Call the parent constructor
this.position = position; >> }
// Getter and Setter for position >> public String getPosition() {
return position; >> }
public void setPosition(String position) {
this.position = position; >> }
@Override >> public String toString() {
return "Employee{position='" + position + "', " + super.toString()
+ "}"; >> } >> }
Student.java (Child Bean 2)
public class Student extends Person { >> private String major;
// Constructor >> public Student(String name, int age, String
major) {
super(name, age); // Call the parent constructor
this.major = major; >> }
public String getMajor() { >> return major; >> }
public void setMajor(String major) { >> this.major = major;
} >> @Override >> public String toString() {
return "Student{major='" + major + "', " + super.toString() + "}"; }
AppConfig.java (Java-based Configuration)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration >> public class AppConfig {
@Bean >> public Person person() {
return new Person("John Doe", 35); // Create a default Person
object >> }
@Bean >> public Employee employee() {
return new Employee("Alice", 28, "Software Engineer"); >> }
@Bean >> public Student student() {
return new Student("Bob", 22, "Computer Science"); >> } >> }
App.java (Main Application Class)
Importorg.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App { >> public static void main(String[] args) {
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
Person person = context.getBean(Person.class);
Employee employee = context.getBean(Employee.class);
Student student = context.getBean(Student.class);
System.out.println(person); >> System.out.println(employee);
System.out.println(student); >> } >> } >> }
Q.5. Write a spring program for bean definition inheritance by using
setter method.
pom.xml.
<dependencies> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> </dependencies>
Person.java (Parent Bean)
public class Person { >> private String name;
private int age; >> // Setter methods for dependency injection
public void setName(String name) { >> this.name = name;
} >> public void setAge(int age) { >> this.age = age;
} >> // Getter methods >> public String getName() {
return name; >> } >> public int getAge() {
return age; >> } >> @Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}"; > } >
}
Employee.java (Child Bean 1)
public class Employee extends Person {
private String position; >> // Setter method for position
public void setPosition(String position) {
this.position = position; >> }
// Getter method for position >> public String getPosition() {
return position; >> } >> @Override
public String toString() {
return "Employee{position='" + position + "', " + super.toString()
+ "}"; >> } >> }
Student.java (Child Bean 2)
public class Student extends Person {
private String major; >> // Setter method for major
public void setMajor(String major) {
this.major = major; >> } >> // Getter method for major
public String getMajor() { >> return major;
} >> @Override >> public String toString() {
return "Student{major='" + major + "', " + super.toString() + "}"; } > }
AppConfig.java (Java-based Configuration)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration >> public class AppConfig {
// Parent bean definition (Person) >> @Bean
public Person person() { >> Person person = new Person();
person.setName("John Doe"); >> person.setAge(40);
@Bean >> public Employee employee() {
Employee employee = new Employee();
employee.setName("Alice"); >> employee.setAge(30);
employee.setPosition("Software Engineer");
return employee; >> }
@Bean >> public Student student() {
Student student = new Student(); >> student.setName("Bob");
student.setAge(22); >> student.setMajor("Computer
Science"); >> return student; >> } >> }
App.java (Main Application Class)
importorg.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App { >> public static void main(String[] args) {
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
Person person = context.getBean(Person.class);
Employee employee = context.getBean(Employee.class);
Student student = context.getBean(Student.class);
System.out.println(person); >> System.out.println(employee);
System.out.println(student); > } > } > }
Q.6. Write a spring program for autowiring by using constructor.
pom.xml
<dependencies> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> </dependencies>
GreetingService.java
public class GreetingService {
public String getGreeting() {
return "Hello, World!"; >> } >> }
UserService.java >> public class UserService {
private GreetingService greetingService;
// Constructor-based autowiring
public UserService(GreetingService greetingService) {
this.greetingService = greetingService;
}
public void greetUser() {
// Use GreetingService to get the greeting
System.out.println(greetingService.getGreeting() + " From
UserService!"); >> } >> }
Step 3: Java Configuration Class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
// Define GreetingService as a bean
@Bean B
public GreetingService greetingService() {
return new GreetingService(); >> }
@Bean
public UserService userService() {
return new UserService(greetingService()); >> } >> }
Step 4: Main Application Class
importorg.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
UserService userService = context.getBean(UserService.class);
userService.greetUser();
>> } >> } >> }
Q.4. Write a spring program for bean scope using singleton.
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> </dependencies>
MessageService.java (Singleton Bean)
public class MessageService { >> private String message;
// Constructor >> public MessageService() {
this.message = "Hello from Singleton Bean!"; >> }
// Getter for the message
public String getMessage() {
return message; >> }
// Setter for the message
public void setMessage(String message) {
this.message = message; >> } >> }
AppConfig.java (Java Configuration)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration >> public class AppConfig {
@Bean
@Scope("singleton") // Explicitly defining singleton scope (default
scope)
public MessageService messageService() {
return new MessageService(); >> } >> }
App.java (Main Application Class)
Import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App { >> public static void main(String[] args) {
// Initialize Spring context using Java configuration
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
// Retrieve the MessageService bean from the Spring container
MessageService messageService1 =
context.getBean(MessageService.class);
MessageService messageService2 =
context.getBean(MessageService.class);
System.out.println("messageService1 hashCode: " +
messageService1.hashCode());
System.out.println("messageService2 hashCode: " +
messageService2.hashCode());
// Print the messages
System.out.println(messageService1.getMessage());
System.out.println(messageService2.getMessage());
// Ensure that the two beans are the same instance
if (messageService1 == messageService2) {
System.out.println("messageService1 and messageService2
are the same instance (Singleton Scope)"); >> } else {
System.out.println("messageService1 and messageService2
are different instances");
} >> } >> >> } >> }

Output :-
messageService1 hashCode: 12345678
messageService2 hashCode: 12345678
Hello from Singleton Bean!
Hello from Singleton Bean!
messageService1 and messageService2 are the same instance
(Singleton Scope)
Q.5. Write a spring DAO program for mapping database rows to java
class by using RowMapper<T> interface.
pom.xml: >> <dependencies> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >> <dependency> >>
<scope>runtime</scope> >> </dependency> >> </dependencies>
Step 2: Define the Java Bean Class (e.g., Employee)
public class Employee { >> private int id; >> private String
name; >> private String department; >> // Constructor
public Employee(int id, String name, String department) {
this.id = id; >> this.name = name;
this.department = department; >> } >> // Getters and setters
public int getId() { >> return id; >> }
public void setId(int id) { >> this.id = id; >> }
public String getName() { >> return name; >> }
public void setName(String name) { >> this.name = name;
} >> public String getDepartment() { >> return department;
} >> public void setDepartment(String department) {
this.department = department; >> } >> @Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "',
department='" + department + "'}"; >> } >> }
Step 3: Implement the RowMapper Interface
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet; >> import java.sql.SQLException;
public class EmployeeRowMapper implements
RowMapper<Employee> {
@Override >> public Employee mapRow(ResultSet
resultSet, int rowNum) throws SQLException {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String department = resultSet.getString("department");
return new Employee(id, name, department); >> } >> }
Step 4: Create the DAO Class
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List; > @Repository > public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;
public EmployeeDAO(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
} >> // Method to fetch employee by id
public Employee getEmployeeById(int id) {
String sql = "SELECT * FROM employees WHERE id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new
EmployeeRowMapper()); >> } >> }
Step 6: Main Application Class
importorg.springframework.context.annotation.AnnotationConfigAp
plicationContext; >> import java.util.List; >> public class App {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
EmployeeDAO employeeDAO =
context.getBean(EmployeeDAO.class);
List<Employee> employees = employeeDAO.getAllEmployees();
for (Employee employee : employees) {
System.out.println(employee); >> }
Employee employeeById = employeeDAO.getEmployeeById(1);
System.out.println("Employee with ID 1: " + employeeById);
} >> } >> }
Q.6. Write a spring DAO program for binding variables in Spring JDBC.

pom.xml:

<dependencies> >>> <dependency>

<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->

</dependency> >> <dependency>


<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >>> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency> >>> <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version> <!-- H2 in-memory database -->
<scope>runtime</scope>
</dependency> >>> </dependencies>

Step 2: Create the Employee Model

public class Employee { >> private int id;


private String name; >> private String department;

public Employee(int id, String name, String department) {

this.id = id; >> this.name = name; >> this.department = department;


} >> // Getters and Setters >> public int getId() { >> return id;
} >> public void setId(int id) { >> this.id = id; } >>
public String getName() { return name;
>>> } >>public void setName(String name) {
this.name = name; >> }
public String getDepartment() { >> return department;

} >> public void setDepartment(String department) {

this.department = department; >> }

@Override >> public String toString() {

return "Employee{id=" + id + ", name='" + name + "', department='" +


department + "'}"; >> } >> }

Step 3: Create the EmployeeDAO for Data Access

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.stereotype.Repository;

import java.util.List; >> @Repository

public class EmployeeDAO { > private JdbcTemplate jdbcTemplate;

public EmployeeDAO(JdbcTemplate jdbcTemplate) {

this.jdbcTemplate = jdbcTemplate; >> }


public Employee getEmployeeById(int id) {

String sql = "SELECT * FROM employees WHERE id = ?";

return jdbcTemplate.queryForObject(sql, new Object[]{id}, new


EmployeeRowMapper()); >> }

public List<Employee> getAllEmployees() {


String sql = "SELECT * FROM employees";

return jdbcTemplate.query(sql, new EmployeeRowMapper()); > }

public int addEmployee(Employee employee) {

String sql = "INSERT INTO employees (id, name, department) VALUES (?, ?, ?)";
return jdbcTemplate.update(sql, employee.getId(),
employee.getName(), employee.getDepartment()); >> }
public int updateEmployeeDepartment(int id, String department) {

String sql = "UPDATE employees SET department = ? WHERE id = ?";

return jdbcTemplate.update(sql, department, id); >> }>> }

Step 4: Create the EmployeeRowMapper Class

import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet; >> import java.sql.SQLException;

public class EmployeeRowMapper implements RowMapper<Employee> {


>> @Override

public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {


return new Employee( >>
rs.getInt("id"),rs.getString("name")rs.getString("department") >> } >> }

Step 7: Create the Main Application Class

importorg.springframework.context.annotation.AnnotationConfigApplication
Context; >> public class App {
public static void main(String[] args) { >> // Initialize Spring context

try (AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext(AppConfig.class)) {

EmployeeDAO employeeDAO = context.getBean(EmployeeDAO.class);

DatabaseInitializer.initializeDatabase(context.getBean(JdbcTemplate.class));

Employee newEmployee = new Employee(3, "Alice Johnson", "Marketing");

employeeDAO.addEmployee(newEmployee);
System.out.println ("All employees:");
employeeDAO.getAllEmployees().forEach(System.out::println);
Employee employee = employeeDAO.getEmployeeById(1);
System.out.println("Employee with ID 1: " + employee);
employeeDAO.updateEmployeeDepartment(1, "Product Management");
System.out.println("Updated employee: " + employeeDAO.getEmployeById(1

} >> } >> }

You might also like