Name: Rameshwar Tiwari
Class: TYBSCIT
Division: B Subject: Spring (Practical)
RollNo: TYITB 43 SubjectTeacher: Prashant Sir
Q1. Write a program to print “HelloWorld” using spring framework.
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class hello {
@GetMapping("/")
String return1(){
return "Hello World";
}
Q2. Write a program to demonstrate dependency injection via
Constructor
Student.java→
package com.example.demo;
public class Student {
private String name;
private String gender;
public Student(String name, String gender) {
super();
this.name = name;
this.gender = gender;
}
public void show() {
System.out.println(name + " " + gender);
}
DicApplication.java→
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@SpringBootApplication
public class DicApplication {
public static void main(String[] args) {
SpringApplication.run(DicApplication.class, args);
ApplicationContext ac = new
ClassPathXmlApplicationContext("ApplicationContext.xml");
Student student = (Student)ac.getBean("s");
student.show();
}
}
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"
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
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="s" class="com.example.demo.Student">
<constructor-arg value="Rameshwar"></constructor-arg>
<constructor-arg value="Tiwari DI with constructor B
43"></constructor-arg>
</bean>
</beans>
Q.3 Write a program to demonstrate dependency injection via
setter method.
Student.java→
package com.example.demo;
public class Student
{
private String name;
private String gender;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getGender()
{
return gender;
}
public void setGender(String gender)
{
this.gender = gender;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
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"
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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="R" class="com.example.demo.Student">
<property name="name" value="Rameshwar Tiwari"></property>
<property name="gender" value="Male"></property>
<property name="age" value="19"></property>
</bean>
</beans>
MainApp.java→
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@SpringBootApplication
public class DiSetterGetterApplication {
public static void main(String[] args) {
SpringApplication.run(DiSetterGetterApplication.class, args);
ApplicationContext ac=new
ClassPathXmlApplicationContext("ApplicationContext.xml");
Student s=(Student)ac.getBean("R");
System.out.println("Student Name is: "+s.getName());
System.out.println("Gender is: "+s.getGender());
System.out.println("Age is: "+s.getAge());
}
Q.4 Write a program to demonstrate Spring AOP before
advice.
Pom.xml→
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
MainAop.java→
package com.example.demo;
public class Employee
{
private String empId;
private String firstName;
private String secondName;
//default constructor
public Employee()
{
}
public String getEmpId()
{
return empId;
}
public void setEmpId(String empId)
{
this.empId = empId;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getSecondName()
{
return secondName;
}
public void setSecondName(String secondName)
{
this.secondName = secondName;
}
}
EmployeeController.java→
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController
{
@Autowired
private EmployeeService employeeService;
@RequestMapping(value = "/add/employee", method = RequestMethod.GET)
public Employee addEmployee(@RequestParam("empId") String empId,
@RequestParam("firstName") String firstName,
@RequestParam("secondName") String secondName)
{
return employeeService.createEmployee(empId, firstName, secondName);
}
@RequestMapping(value = "/remove/employee", method =
RequestMethod.GET)
public String removeEmployee( @RequestParam("empId") String empId)
{
employeeService.deleteEmployee(empId);
return "Employee removed";
}
}
EmpoyeeService→
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService
{
public Employee createEmployee( String empId, String fname, String sname)
{
Employee emp = new Employee();
emp.setEmpId(empId);
emp.setFirstName(fname);
emp.setSecondName(sname);
return emp;
}
public void deleteEmployee(String empId)
{
}
}
EmployeeServiceAspect.java→
package com.example.demo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class EmployeeServiceAspect
{
@Before(value = "execution(* com.example.demo.EmployeeService.*(..)) and
args(empId, fname, sname)")
public void beforeAdvice(JoinPoint joinPoint, String empId, String fname, String
sname) {
System.out.println("Before method:" + joinPoint.getSignature());
System.out.println("Creating Employee with first name - " + fname + ", second
name - " + sname + " and id - " + empId);
}
}
Q.5 Write a program to demonstrate Spring AOP after
advice.
Pom.xml→
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
MainAop.java→
package com.example.demo;
public class Employee
{
private String empId;
private String firstName;
private String secondName;
//default constructor
public Employee()
{
}
public String getEmpId()
{
return empId;
}
public void setEmpId(String empId)
{
this.empId = empId;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getSecondName()
{
return secondName;
}
public void setSecondName(String secondName)
{
this.secondName = secondName;
}
}
EmployeeController.java→
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController
{
@Autowired
private EmployeeService employeeService;
@RequestMapping(value = "/add/employee", method = RequestMethod.GET)
public Employee addEmployee(@RequestParam("empId") String empId,
@RequestParam("firstName") String firstName,
@RequestParam("secondName") String secondName)
{
return employeeService.createEmployee(empId, firstName, secondName);
}
@RequestMapping(value = "/remove/employee", method =
RequestMethod.GET)
public String removeEmployee( @RequestParam("empId") String empId)
{
employeeService.deleteEmployee(empId);
return "Employee removed";
}
}
EmpoyeeService→
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService
{
public Employee createEmployee( String empId, String fname, String sname)
{
Employee emp = new Employee();
emp.setEmpId(empId);
emp.setFirstName(fname);
emp.setSecondName(sname);
return emp;
}
public void deleteEmployee(String empId)
{
}
}
EmployeeServiceAspect.java→
package com.example.demo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class EmployeeServiceAspect
{
@After(value = "execution(* com.example.demo.EmployeeService.*(..))
and args(empId, fname, sname)")
public void afterAdvice(JoinPoint joinPoint, String empId, String fname,
String sname) {
System.out.println("After method:" + joinPoint.getSignature());
System.out.println("Creating Employee with first name - " + fname + ",
second name - " + sname + " and id - " + empId);
}
}
Q.6 Write a program to demonstrate Spring AOP around
advice.
BankAspect.java→
package com.example.demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//Enables the spring AOP functionality in an application
@Aspect
@Component
public class BankAspect
{
//Displays all the available methods i.e. the advice will be called for all
the methods
@Pointcut(value= "execution(* com.example.demo.BankService.*(..))")
private void logDisplayingBalance()
{
}
//Declares the around advice that is applied before and after the
method matching with a pointcut expression
@Around(value= "logDisplayingBalance()")
public void aroundAdvice(ProceedingJoinPoint jp) throws Throwable
{
System.out.println("The method aroundAdvice() before invokation of
the method " + jp.getSignature().getName() + " method");
try
{
jp.proceed();
}
finally
{
}
System.out.println("The method aroundAdvice() after invokation of the
method " + jp.getSignature().getName() + " method");
}
}
BankService.java→
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class BankService
{
public void displayBalance(String accNum)
{
System.out.println("Inside displayBalance() method");
if(accNum.equals("12345"))
{
System.out.println("Total balance: 10,000");
}
else
{
System.out.println("Sorry! wrong account number.");
}
}
}
MainClass→
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import
org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy
public class Prac6AroundAdviceApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context=
SpringApplication.run(Prac6AroundAdviceApplication.class, args);
BankService bank = context.getBean(BankService.class);
// Displaying balance in the account
String accnumber = "12345";
bank.displayBalance(accnumber);
// Closing the context object
context.close();
}
}
Q7.Write a program to demonstrate Spring AOP after returning
advice.
Account.java→
package com.example.demo;
public class Account
{
private String accountNumber;
private String accountType;
public Account(String accountNumber, String accountType)
{
super();
this.accountNumber = accountNumber;
this.accountType = accountType;
}
public String getAccountType()
{
return accountType;
}
public String getAccountNumber()
{
return accountNumber;
}
@Override
public String toString()
{
return "Account [accountNumber=" + accountNumber+ ", accountType=" +
accountType + "]";
}
}
AccountServiceImpl.java→
package com.example.demo;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.stereotype.Service;
@Service
public class AccountServiceImpl implements AccountService
{
//storing account detail in the HashMap
private static Map<String,Account> map = null;
static
{
map = new HashMap<>();
//adding account detail in the map
map.put("M4546779", new Account("10441117000", "Saving Account"));
map.put("K2434567", new Account("10863554577", "Current Account"));
}
@Override
public Account getAccountByCustomerId(String customerId) throws Exception
{
if(customerId ==null)
{
throw new Exception("Invalid! Customer Id");
}
Account account= null;
Set<Entry<String, Account>> entrySet = map.entrySet();
for (Entry<String, Account> entry : entrySet)
{
if(entry.getKey().equals(customerId))
{
account= entry.getValue();
}
}
return account;
}
}
AccountService.java→
package com.example.demo;
//creating interface that throws exception if the customer id not
found
public interface AccountService
{
public abstract Account getAccountByCustomerId(String customerId)
throws Exception;
}
AccountAspect.java→
package com.example.demo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AccountAspect
{
//implementing after returning advice
@AfterReturning(value="execution(*
com.example.demo.AccountServiceImpl.*(..))",returning="account")
public void afterReturningAdvice(JoinPoint joinPoint, Account account)
{
System.out.println("After Returing method:"+joinPoint.getSignature());
System.out.println(account);
}
}
Mainclass.java→
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class Prac7AfterReturningApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ac
=SpringApplication.run(Prac7AfterReturningApplication.class, args);
AccountService accountService =
ac.getBean("accountServiceImpl", AccountServiceImpl.class);
Account account;
try
{
account = accountService.getAccountByCustomerId("K2434567");
if(account != null)
System.out.println(account.getAccountNumber()+"\t"+account.getAc
countType());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Q.8 Write a program to demonstrate Spring AOP pointcuts.
Logging.java→
package com.example.demo;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
@Aspect
public class Logging {
@Pointcut("execution(* com.example.demo.*.*(..))")
private void selectAll(){}
@Bef0ore("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
}
MainApp.java→
package com.example.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student");
student.getName();
student.getAge();
}
}
Student.java→
package com.example.demo;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Q.9 Write a program in Spring JDBC to demonstrate
ResultSetExtractor Interface.
Book.java→
package com.example.demo;
public class Book {
private String name;
private int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
BookController.java→
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
@Autowired
BookRepo br;
@PostMapping("/add")
public int addData(@RequestBody Book b) {
return br.addBook(b);
}
@GetMapping("/view")
public List<Book> getData(Book b){
return br.getBooks(b);
}
}
BookRepo→
package com.example.demo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepo {
@Autowired
JdbcTemplate jt;
public int addBook(Book b) {
List<Book> lb = jt.query(
"select * from Book where name =
'"+b.getName()+"'",
new RowMapper<Book>() {
@Override
public Book
mapRow(ResultSet rs, int rowNum) throws SQLException {
Book bn = new Book();
bn.setName(rs.getString(1));
bn.setPrice(rs.getInt(2));
return bn;
}
}
);
if(lb.size()>0) {
int price = b.getPrice() +
lb.get(0).getPrice();
return jt.update("update book set
price = '"+price+"' where name = '"+b.getName()+"'");
}else {
return jt.update("insert into Book
values(?,?)", new Object[] {b.getName(), b.getPrice()});
}
}
public List<Book> getBooks(Book b){
return jt.query(
"select * from Book",
new
ResultSetExtractor<List<Book>>() {
@Override
public List<Book>
extractData(ResultSet rs) throws SQLException, DataAccessException
{
List<Book> nlb = new
ArrayList<Book>();
while(rs.next()) {
Book bn = new
Book();
bn.setName(rs.getString(1));
bn.setPrice(rs.getInt(2));
nlb.add(bn);
}
return nlb;
}
}
);
}
}
BookMain.java→
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JdbcProjectApplication {
public static void main(String[] args) {
SpringApplication.run(JdbcProjectApplication.class,
args);
}
}
Application.properties→
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/tyit
Q10. Write a program to demonstrate RowMapper interface to
fetch the records from the database.
RowMapperMinaClass.java→
package com.example.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RowMapperJdbcApplication {
public static void main(String[] args) {
SpringApplication.run(RowMapperJdbcApplic
ation.class, args);
}
}
Student.java→
package com.example.demo;
public class Student {
// member variables
private int id;
private String name;
private String department;
// getters and setters method
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;
}
// toString() method
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", department="
+ department + "]";
}
}
StudentDao.java→
package com.example.demo;
import java.util.List;
public interface StudentDao {
// this method will return all
// the details of the students
public List<Student> getAllStudentDetails();
DaoIMplem.java→
package com.example.demo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class StudentDaoImpl implements StudentDao{
// Defining JdbcTemplate as member variable in order
// to use the query() method of the JdbcTemplate's class
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// This method will return the list
// of all the details of student
public List<Student> getAllStudentDetails() {
// Implementation of RowMapper interface
return jdbcTemplate.query("SELECT * FROM student", new
RowMapper<Student>() {
public Student mapRow(ResultSet rs, int rowNum) throws
SQLException {
Student student = new Student();
student.setId(rs.getInt(1));
student.setName(rs.getString(2));
student.setDepartment(rs.getString(3));
return student;
}
});
}
}
TestRowMapper.java→
package com.example.demo;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;
import java.util.List;
public class TestRowMapper {
public static void main(String[] args) {
// Reading the application-context file using
// class path of spring context xml file
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("application-context.xml");
// Spring check the blueprint for studentDao bean
// from application-context.xml file and return it
StudentDaoImpl studentDaoImpl =
(StudentDaoImpl)context.getBean("studentDao");
// Getting student data
List<Student> studentDetailList =
studentDaoImpl.getAllStudentDetails();
for(Student index : studentDetailList) {
System.out.println(index);
}
}
}