Friday, October 28, 2022

Spring - Beans AutoWiring

  • In general, in spring applications, if we want to inject dependent values in setter method dependency injection or in constructor dependency injection we have to use <property> or <constructor-arg> tags under <bean> tag. If we want to inject simple values like primitive values, string values then we have to use "value" attribute and if we want to inject Secondary data type elements like Objects then we have to use "ref" attribute or we have to use <ref> tag in beans configuration file.
  • In spring applicatins , if we want to inject dependent bean objects to another bean object automatically with out providing <property> tags and <constructor-arg> tags then we have to use "Autowiring" feature
  • "Autowiring" feature of spring framework will make the IOC Container to inject dependent objects to the bean objects automatically on the basis of the properties names or on the basis of properties types with out checking <property> tags and <constructor-arg> tags.



There are four ways to manage auto wiring in Spring applications.

  1. XML Based Autowiring
  2. Annotation Based Autowiring
  3. Auto-Discovery[Stereo Types]
  4. Java Based Autowiring

1. XML Based Autowiring

  • In this approach, If we want to provide autowiring in spring applications then we have to use "autowire" attribute in <bean> tag

  • Example:
    • <bean id="--" class="--" autowire="value">
  • Here value may be either of the following "auto wiring modes". 

    1. no
    2. byName
    3. byType 
    4. constructor

1.No

  • It is representing "no" autowiring for the beans injection, we must provide explicit configuration for the beans injection.

2.ByName

  • It will provide autowiring on the basis of the properties names. In this autowiring mode, IOC Conainer will search for dependent bean objects by matching bean properties names with the identity values of the beans configuration in spring configuration file.

3.ByType

  • It will provide autowiring on the basis of the properties data types. In this autowiring mode, IOC Container will identify the dependent bean objects by matching properties data types with the bean data types[ class attribute values] in bean configuration.

  • Note: In Beans configuration file, only one bean definition must be existed with the same type , if we provide more than one bean configuration with the same type in beans configuration file then IOC Container will rise an exception.

4.Constructor

  • It is same as "byType" autowiring mode, but, "byType" autowiring will provide setter method dependency injection and "constructor" autowiring mode will provide constructor dependency injection on the basis of the types.

Example:

Address.java

package com.cloud.beans;
public class Address {
  private String hno;
  private String street; 
  private String city; 
  private String state;
 
  setXXX() 
  getXXX()
}

Account.java

package com.cloud.beans; 
public class Account {

  private String accNo; 
  private String accName; 
  private String accType; 
  private long balance;

  setXXX() 
  getXXX()
}

Employee.java

package com.cloud.beans; public class Employee {
   private String eid; 
   private String ename; 
   private Address eaddr; 
   private Account eacc;

   setXXX()
   getXXX()

   public void getEmpDetails(){ 
      System.out.println("Employee Details"); 
      System.out.println("---------------------"); 
      System.out.println("Employee Id :"+eid); 
      System.out.println("Employee Name :"+ename); 
      System.out.println();
      
      System.out.println("Employee Address Details");
      System.out.println("--------------------------"); 
      System.out.println("House Number:"+eaddr.getHno());
      System.out.println("Street :"eaddr.getHno());
      System.out.println("City   :"eaddr.getCity());
      System.out.println("State  :"eaddr.getState());
      System.out.println();
      
      System.out.println("Employee Account Details"); 
      System.out.println("-------------------"); 
      System.out.println("Account NUmber :"+eacc.getAccNo()); 
      System.out.println("Account Name :"+eacc.getAccName()); 
      System.out.println("Account Type :"+eacc.getAccType()); 
      System.out.println("Account Balance:"+eacc.getBalance()); 
   }

}

applicationContext.xml

 <beans>
   <bean id="eaddr" class="com.cloud.beans.Address">
      <property name="hno" value="23/3rt"/> 
      <property name="street" value="PS Road"/> 
      <property name="city" value="Hyd"/> 
      <property name="state" value="Tel"/>
   </bean>
   
   <bean id="eacc" class="com.cloud.beans.Account">
      <property name="accNo" value="abc123"/> <property name="accName" value="cloud"/>
      <property name="accType" value="Savings"/>
      <property name="balance" value="20000"/> </bean>
   <bean id="emp" class="com.cloud.beans.Employee" autowire="byName"> <property name="eid" value="E-111"/>
      <property name="ename" value="cloud"/> <!--
      <property name="eaddr" ref="eaddr"/> <property name="eacc" ref="eacc"/>
   </bean>
</beans>

Test.java

package com.cloud.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import com.cloud.beans.Employee;

public class Test {
   public static void main(String[] args){
      ApplicationContext context=
         new ClassPathXmlApplicationContext("applicationContext.xml");
      Employee emp=(Employee)context.getBean("emp");
      emp.getEmpDetails();
   }
}

  • If we want to provide example for "constructor" autowiring then we have to use the following components in the above example

Example:

Address.java

package com.cloud.beans;
public class Address { 
   private String hno;
   private String street;
   private String city; 
   private String state;
   
   setXXX() 
   getXXX()
}

Account.java

package com.cloud.beans; 
public class Account {
   private String accNo; 
   private String accName; 
   private String accType; 
   private long balance;
   
   setXXX()
   getXXX() 
}

Employee.java

 public class Employee { 
   private String eid;
   private String ename; 
   private Address eaddr; 
   private Account eacc;

   public Employee(String eid, String ename, 
      Address eaddr, Account eacc ){ 
      this.eid=eid;
      this.ename=ename;
      this.eaddr=eaddr; 
      this.eacc=eacc;
   }

   public void getEmpDetails(){ 
      System.out.println("Employee Details"); 
      System.out.println("---------------------"); 
      System.out.println("Employee Id :"+eid); 
      System.out.println("Employee Name :"+ename); 
      System.out.println();
     
      System.out.println("Employee Address Details"); 
      System.out.println("--------------------------"); 
      System.out.println("House Number:"+eaddr.getHno());
      System.out.println("Street :"+eaddr.getStreet());
      System.out.println("City   :"+eaddr.getCity());
      System.out.println("State  :"+eaddr.getState());
      System.out.println();

      System.out.println("Employee Account Details"); 
      System.out.println("-------------------"); 
      System.out.println("Account NUmber :"+eacc.getAccNo()); 
      System.out.println("Account Name :"+eacc.getAccName()); 
      System.out.println("Account Type :"+eacc.getAccType()); 
      System.out.println("Account Balance:"+eacc.getBalance()); 
   }
}
applicationContext.xml
<beans>
  <bean id="eaddr" class="com.cloud.beans.Address">
    same as above </bean>
  <bean id="eacc" class="com.cloud.beans.Account"> 
      same as above </bean>
  <bean id="emp" class="com.cloud.beans.Employee" 
      autowire="constructor">
    <constructor-arg name="eid" value="E-111"/>
    <constructor-arg name="ename" value="cloud"/> </bean>
</beans>

Test.java

package com.cloud.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import com.cloud.beans.Employee;

public class Test {
  public static void main(String[] args){
    ApplicationContext context=
      new ClassPathXmlApplicationContext("applicationContext.xml");
    Employee emp=(Employee)context.getBean("emp");
    emp.getEmpDetails();
  }
}

  • Note: If we want to block any bean object in autowiring then we have to use "autowire- candidate" attribute with "false" value in <bean> tag in beans configuration file.

Exampe:

 <beans>
  <bean id="scourse" class="com.cloud.beans.Course" autowire-candidate="false"></bean>
  <bean id="student" class="com.cloud.beans.Student" autowire="byType"></bean>
</beans>
2. Annotation s for Autowiring:

  • To implement Autowiring in Spring applications with out providing autowiring configuration in spring configuration file , we have to use the following annotations provided by spring framework.

    1. @Required 
    2. @Autowired 
    3. @Qualifier

1.@Required

  • This annotation will make IOC Container to inject a particular bean object in another bean object is mandatory. We have to use this annotation at method level, that is, just before setXXX() method. After providing this annotation, if we are not providing the respectiove bean injection then IOC Container will rise an exception .

2.@Autowired

  • This annotation is able to represent auto wiring in bean classes, it will be used at method level, field level and local variables level in constructor dependency injection.
  • Note: If we provide "required" argument with "false" value in @Autowired annotation then it is not required to use @Required annotationi.
  • Note: This annotation is following "byType" autowiring internally in spring applications, If we want to use this annotation then we must have only one bean configuration withh the respective type in configuration file, if we have more than one bean configuration with the same type then IOC Container will rise an exception.

3.@Qualifier

  • In the case of "byType" autowiring mode, that is, in the case of @Autowired annotation configuration file must provide only one bean configuration with the respective type, if we provide more than one bean configuration with the same type then IOC Container will rise an exception. 
  • In this context, to resolve the ambiguity of beans injection we have to use "@Qualifier" annotation, it will be used to specify a particular bean object among the multiple beans of the same type for injection.
    • Example: @Qualifier("bean_Identity")

Example:

Student.java

package com.cloud.beans;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.beans.factory.annotation.Required;

public class Student { 
  private String sid;
  private String sname; 
  private Course scourse;

  public String getSid() {
    return sid; 
  }

  public void setSid(String sid) {
    this.sid = sid; 
  }

  public String getSname() {
    return sname; 
  }

  public void setSname(String sname) {
    this.sname = sname; 
  }

  public Course getScourse() {
    return scourse; 
  }

  @Autowired(required=true)
  //@Required
  @Qualifier("adv_Java")
  public void setScourse(Course scourse) {
    this.scourse = scourse; 
  }

  public void getStudentDetails(){
    System.out.println("Student Details"); 
    System.out.println("--------------------"); 
    System.out.println("Student Id :"+sid); 
    System.out.println("Student Name :"+sname); 
    
    System.out.println("Course Details"); 
    System.out.println("----------------"); 
    System.out.println("Course Id :"+scourse.getCid()); 
    System.out.println("Course Name :"+scourse.getCname()); 
    System.out.println("Course Cost :"+scourse.getCcost());

  } 
}

Course.java

package com.cloud.beans; 
public class Course {
  private String cid; 
  private String cname; 
  private int ccost;
  setXXX()
  getXXX() 
}

applicationContext.xml

  <beans >
  <context:annotation-config/>
  <bean id="core_Java" class="com.cloud.beans.Course">
    <property name="cid" value="C-111"/> 
    <property name="cname" value="Core Java"/>
    <property name="ccost" value="10000"/>
  </bean>

  <bean id="adv_Java" class="com.cloud.beans.Course">
    <property name="cid" value="C-111"/> 
    <property name="cname" value="Adv Java"/> 
    <property name="ccost" value="20000"/>
  </bean>

  <bean id="std" class="com.cloud.beans.Student" >
    <property name="sid" value="S-111"/>
    <property name="sname" value="cloud"/> 
  </bean>
</beans>

Test.java

package com.cloud.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import com.cloud.beans.Student;

public class Test {
  public static void main(String[] args)throws Exception {
    ApplicationContext context=new 
      ClassPathXmlApplicationContext("applicationContext.xml");
    Student std=(Student)context.getBean("std");
    std.getStudentDetails();
  }

}

  • If we want to use @Autowired annotation for constructor dependency injection then we have to use @Autowired annotation just above of the respective constructor and we have to use @Qualifier annotation along with with the Bean parameter in constructor.

Example:

Student.java

package com.cloud.beans;

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.beans.factory.annotation.Required;

public class Student { 

  private String sid;
  private String sname; 
  private Course scourse;
  
  @Autowired
  public Student(String sid, String sname, 
    @Qualifier("adv_Java")Course scourse){
    this.sid=sid; 
    this.sname=sname; 
    this.scourse=scourse;
  }
  
  public void getStudentDetails(){
    System.out.println("Student Details"); 
    System.out.println("--------------------"); 
    System.out.println("Student Id :"+sid); 
    System.out.println("Student Name :"+sname); 
    
    System.out.println("Course Details"); 
    System.out.println("----------------"); 
    System.out.println("Course Id :"+scourse.getCid()); 
    System.out.println("Course Name :"+scourse.getCname()); 
    System.out.println("Course Cost :"+scourse.getCcost());
  }
}

Course.java

package com.cloud.beans; 
public class Course {
  private String cid; 
  private String cname;
  private int ccost;
  setXXX()
  getXXX() 
}

applicationContext.xml

<beans>
  <context:annotation-config/>
  <bean id="core_Java" class="com.cloud.beans.Course">
    <property name="cid" value="C-111"/> 
    <property name="cname" value="Core Java"/> 
    <property name="ccost" value="10000"/>
  </bean>
  
  <bean id="adv_Java" class="com.cloud.beans.Course">
    <property name="cid" value="C-111"/> 
    <property name="cname" value="Adv Java"/>
    <property name="ccost" value="20000"/>
  </bean>
  <bean id="std" class="com.cloud.beans.Student" >
    <constructor-arg name="sid" value="S-111"/>
    <constructor-arg name="sname" value="cloud"/> 
  </bean>
</beans>

Test.java

package com.cloud.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import com.cloud.beans.Student;

public class Test {
  public static void main(String[] args)throws Exception {
    ApplicationContext context=
      new ClassPathXmlApplicationContext("applicationContext.xml");

    Student std=(Student)context.getBean("std"); 
    std.getStudentDetails();
  }
}
3. Auto-Discovery[Stereo Types]

  • This mechanism will provide the autowiring beans objects with out using <bean> configuration in configuration file.
  • To use this mechanism in Spring applications then we have to use the following annotations provided by spring framework in the package "org.springframework.stereotype"

  • 1.@Component: 

    • It will represent a component which is recognized by Spring Container.

  • 2.@Repository: 

    • It will represent a class as Model Driven , that is, DAO. 

  • 3.@Service :

    •  It will represent a class as Service class.

  • 4.@Controller: 

    • It will represent a class as Controller class, it will be used in Spring WEB-MVC Module.

  • Note: If we want to use these annotations in Spring applications then we must provide the following tag in spring configuration file.

    • <context:component-scan base-package="---"/>

 Example:

<context:component-scan base-package="com.cloud.service"/> 
<context:component-scan base-package="com. cloud.dao"/> 
<context:component-scan base-package="com.cloud.controller"/>

  • If we provide the above tag in spring configuration file then IOC Container will scan the specified packages and recognize the classes which are annotated with @Component, @Repository, @Service and @Controller then Container will create bean objects with out checking beans configurations in configuration file.

Example:

AccountDao.java

package com.cloud.dao;
import com.cloud.dto.Account;

public interface AccountDao {
  public String create(String accNo, String accName, 
    String accType, int balance); public String search(String accNo);

    public Account getAccount(String accNo);
    public String update(String accNo,
       String accName, String accType, int balance); 
    public String delete(String accNo);
}

AccountDaoImpl.java

package com.cloud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.ResultSet;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.cloud.dto.Account; import oracle.jdbc.pool.OracleDataSource;

//@Repository("accDao")
@Component("accDao")
public class AccountDaoImpl implements AccountDao {

  String status = "";
 
  @Autowired(required=true)
  private OracleDataSource dataSource;
  
  @Override
  public String create(String accNo, String accName, String accType, int balance) {
  try {
    PreparedStatement pst = 
      con.prepareStatement("select * from account where accNo=?");

    Connection con = dataSource.getConnection();
    pst.setString(1, accNo);
    ResultSet rs = pst.executeQuery(); boolean b = rs.next();
    
    if(b == true) {
       status="existed"; 
    } else {
        pst = con.prepareStatement("insert into account  values(?,?,?,?)");
        pst.setString(1, accNo); 
        pst.setString(2, accName); 
        pst.setString(3, accType);
        pst.setInt(4, balance); 
        pst.executeUpdate(); 
        status="success";
    }
  } catch (Exception e) {
    status = "failure";
    e.printStackTrace(); 
  }
  return status; 
  }

  @Override
  public String search(String accNo) {
   try {
     Connection con = dataSource.getConnection();
      PreparedStatement pst = con.prepareStatement("select * from account where accNo = ?");
      pst.setString(1, accNo);
    
      ResultSet rs = pst.executeQuery(); boolean b = rs.next();
    
      if(b == true) {
        status = "[ACCNO:"+rs.getString("ACCNO")+",ACCNAME:"+rs.getString("ACCNAME")+",ACCTYP E:"+rs.getString("ACCTYPE")+",BALANCE:"+rs.getInt("BALANCE")+"]"; 
      } else {
        status = "Account Not Existed"; }
    } 
    catch (Exception e) {
      e.printStackTrace(); 
   }
  return status; 
 }

 @Override
 public Account getAccount(String accNo) {
  Account acc = null;
  try {
    Connection con = dataSource.getConnection(); 
    PreparedStatement pst = con.prepareStatement("select * from
      account where accNO = ?"); 
    pst.setString(1, accNo);

    ResultSet rs = pst.executeQuery(); 
    boolean b = rs.next();

    if(b == true) {
      acc = new Account(); 
      acc.setAccNo(rs.getString("ACCNO")); 
      acc.setAccName(rs.getString("ACCNAME")); 
      acc.setAccType(rs.getString("ACCTYPE")); 
      acc.setBalance(rs.getInt("BALANCE"));

    }else {
      acc = null;
    }
  }catch (Exception e) {
    e.printStackTrace(); 
  }
  return acc;
 }

@Override
public String update(String accNo, String accName, 
  String accType, int balance) {
  try {
   Connection con = dataSource.getConnection();
   PreparedStatement pst = con.prepareStatement("update account set 
        ACCNAME = ?, ACCTYPE = ?, BALANCE = ? where ACCNO = ?"); pst.setString(1, accName);
   pst.setString(2, accType); 
   pst.setInt(3, balance);
   pst.setString(4, accNo); 
    pst.executeUpdate(); 
    status = "success";
  } catch (Exception e) { 
    status = "failure";
    e.printStackTrace();
  }
 return status; 
}

@Override
public String delete(String accNo) {
try {
  Connection con = dataSource.getConnection(); 
  PreparedStatement pst = con.prepareStatement("select * from
    account where accNO = ?"); pst.setString(1, accNo);

  ResultSet rs = pst.executeQuery(); boolean b = rs.next();

  if(b == true) {
    pst = con.prepareStatement("delete from account where accNo
    pst.setString(1, accNo); pst.executeUpdate(); status = "success";
  }else {
    status = "notexisted";
  }
 } catch (Exception e) {
    status = "failure";
    e.printStackTrace(); 
 }
 return status; 
 }
}

AccountService.java 

<beans>
    <bean ..... >
        <constructor-arg value="--"/> <constructor-arg> value </constructor-arg>
    </bean>
    ---- 
</beans>

Account.java

package com.cloud.service;

import com.cloud.dto.Account;

  public interface AccountService {
    public String createAccount(String accNo, String accName, 
        String accType, int balance);

    public String searchAccount(String accNo);
    public Account getAccount(String accNo);
    public String updateAccount(String accNo, String accName, String accType, int balance);
    public String deleteAcount(String accNo); 
  }
AccountServiceImpl.java
package com.cloud.service;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service;
import com.cloud.dao.AccountDao; import com.cloud.dto.Account;

@Service("accService")
public class AccountServiceImpl implements AccountService {

  @Autowired(required=true)
  private AccountDao dao;

  @Override
  public String createAccount(String accNo, String accName, 
    String accType, int balance) {
      return dao.create(accNo, accName, accType, balance);
  }

  @Override
  public String searchAccount(String accNo) {
    return dao.search(accNo); 
  }

  @Override
  public Account getAccount(String accNo) {
    return dao.getAccount(accNo); 
  }

  @Override
  public String updateAccount(String accNo, String accName,
     String accType, int balance) {
    return dao.update(accNo, accName, accType, balance); 
  }

  @Override
  public String deleteAcount(String accNo) {
    return dao.delete(accNo); 
  }
}

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:component-scan base-package="com.cloud.service"/> 
    <context:component-scan base-package="com.cloud.dao"/> 

    <bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
      <property name="URL" value="jdbc:oracle:thin:@localhost:1521:xe"/> 
      <property name="user" value="system"/>
      <property name="password" value="cloud"/>
    </bean> 
</beans>

Test.java

package com.cloud.test;

import java.io.BufferedReader; import java.io.InputStreamReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cloud.dao.AccountDao; import com.cloud.dto.Account;
import com.cloud.service.AccountService;

public class Test {

      public static void main(String[] args)throws Exception { ApplicationContext context = new
            
            ClassPathXmlApplicationContext("applicationContext.xml"); 
            
            AccountService accService = (AccountService)context.getBean("accService"); 
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            
            while(true) { 
                  System.out.println();
                  System.out.println("Account Operations Menu"); 
                  System.out.println("1.Create Account"); 
                  System.out.println("2.Search Account"); 
                  System.out.println("3.Update Account"); 
                  System.out.println("4.Delete Account"); 
                  System.out.println("5.Exit"); 
                  System.out.print("Your Option :");

                  int option = Integer.parseInt(br.readLine()); String status = "";

                  String accNo = "", accName = "", accType = ""; int balance = 0;

                  switch(option) {
                    case 1:
                        System.out.print("Account Number :");
                        accNo = br.readLine(); 

                        System.out.print("Account Name :"); 
                        accName = br.readLine(); 

                        System.out.print("Account Type :"); 
                        accType = br.readLine(); 

                        System.out.print("Balance :"); 
                        balance = Integer.parseInt(br.readLine());

                        status = accService.createAccount(accNo, accName, accType,balance);
                        
                        if(status.equals("success")) {
                              System.out.println("Account Created Successfully"); 
                        }
                        
                        if(status.equals("failure")){
                              System.out.println("Account Creation Failure"); 
                        }
                        if(status.equals("existed")) {
                              System.out.println("Account Existed Already"); 
                        }
                     break;
                    
                    case 2:
                        System.out.print("Account Number :");
                        accNo = br.readLine();
                        status = accService.searchAccount(accNo); 
                        System.out.println("Account Details :"+status); 
                        break;
                    case 3:
                        System.out.print("Account Number :"); 
                        accNo = br.readLine();
                        Account acc = accService.getAccount(accNo); 

                        if(acc == null) {
                              System.out.println("Status :Account Not Existed"); 
                        }else {
                              Account acc_New = new Account(); 
                              acc_New.setAccNo(accNo)

                        System.out.print("Account Name : Old Value :"+acc.getAccName()+" New Value :");
                        String accName_New = br.readLine(); 

                        if(accName_New == null || accName_New.equals("")) {
                              acc_New.setAccName(acc.getAccName()); }else {
                              acc_New.setAccName(accName_New); 
                        }
                              
                        System.out.print("Account Type : Old Value :"+acc.getAccType()+" New Value :");
                        String accType_New = br.readLine(); 

                        if(accType_New == null || accType_New.equals("")) {
                              acc_New.setAccType(acc.getAccType()); }else {
                               acc_New.setAccType(accType_New); 
                        }
                        
                        System.out.print("Account Balance : Old Value :"+acc.getBalance()+" New Value :");
                        String bal = br.readLine(); 

                        if(bal == null || bal.equals("")) {
                              acc_New.setBalance(acc.getBalance()); }else {
                              int balance_New = Integer.parseInt(bal);
                              acc_New.setBalance(balance_New); 
                        }
                        
                        status = accService.updateAccount(acc_New.getAccNo(), acc_New.getAccName(),acc_New.getAccType(), acc_New.getBalance());
                        
                        if(status.equals("success")) { 
                              System.out.println("Account Updated");
                        } 

                        if(status.equals("failure")) {
                              System.out.println("Account Updation Failure"); 
                        }
                  break;

                  case 4:
                        System.out.print("Account Number :"); 
                        accNo = br.readLine();
                        status = accService.deleteAcount(accNo); 

                        if(status.equals("success")) {
                              System.out.println("Account Deleted Successfully"); 
                        }
                        
                        if(status.equals("failure")) {
                              System.out.println("Account Deletion Failure"); 
                        }
                        
                        if(status.equals("notexisted")) {
                              System.out.println("Account Not Existed"); 
                        }
                  break;

                  case 5:
                        System.out.println("***** ThankQ for Using Account Operations App*****");
                        
                  break; 

                  default:
                        System.out.println("Enter Number from 1,2,3,4 and 5");
                  break
            }
      }
}
4.Java Based Autowiring

AccountDao.java

package com.cloud.dao;
import com.cloud.dto.Account;
public interface AccountDao {
      public String create(String accNo, String accName, String accType, int balance); 
      public String search(String accNo);
      public Account getAccount(String accNo);
      public String update(String accNo, String accName, String accType, int balance); 
      public String delete(String accNo);
}

AccountDaoImpl.java

package com.cloud.dao;
import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.ResultSet;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.cloud.dto.Account; import oracle.jdbc.pool.OracleDataSource;

//@Repository("accDao")
@Component("accDao")

public class AccountDaoImpl implements AccountDao {

   String status = ""; @Autowired(required=true)
   private OracleDataSource dataSource;

   @Override
   public String create(String accNo, String accName, 
      String accType, int balance) {
      try {
         Connection con = dataSource.getConnection();
         
         PreparedStatement pst = con.prepareStatement("select * from account where accNo=?");
         pst.setString(1, accNo);

         ResultSet rs = pst.executeQuery(); boolean b = rs.next();

         if(b == true) {
            status="existed"; }else {
            pst = con.prepareStatement("insert into account values(?,?,?,?)");
            pst.setString(1, accNo); 
            pst.setString(2, accName); 
            pst.setString(3, accType); 
            pst.setInt(4, balance); 
            pst.executeUpdate(); 
            status="success";
         }
      } catch (Exception e) {
         status = "failure";
         e.printStackTrace(); 
      }
      return status; 
   }

   @Override
   public String search(String accNo) {
      try {
         Connection con = dataSource.getConnection(); 
         PreparedStatement pst = con.prepareStatement("select * from account where accNo = ?"); 
         pst.setString(1, accNo);

         ResultSet rs = pst.executeQuery(); 
         boolean b = rs.next();

         if(b == true) {
            status = "[ACCNO:"+rs.getString("ACCNO")+",ACCNAME:"+rs.getString("ACCNAME")+",ACCTYPE:"+rs.getString("ACCTYPE")+",BALANCE:"+rs.getInt("BALANCE")+"]"; 
         } else {
            status = "Account Not Existed"; 
         }
      } catch (Exception e) {
         e.printStackTrace(); 
      }
    return status; 
   }

   @Override
   public Account getAccount(String accNo) {
      Account acc = null;
      try {
         Connection con = dataSource.getConnection(); 
         PreparedStatement pst = con.prepareStatement("select * from
            account where accNO = ?"); pst.setString(1, accNo);

         ResultSet rs = pst.executeQuery(); boolean b = rs.next();

         if(b == true) {
            acc = new Account(); 
            acc.setAccNo(rs.getString("ACCNO")); 
            acc.setAccName(rs.getString("ACCNAME")); 
            acc.setAccType(rs.getString("ACCTYPE")); 
            acc.setBalance(rs.getInt("BALANCE"));
         }else {
            acc = null; 
         }
      } catch (Exception e) {
         e.printStackTrace(); 
      }
   return acc; 
  }    

 @Override
 public String update(String accNo, String accName, String accType, int balance) {
 try {
    Connection con = dataSource.getConnection();
      PreparedStatement pst = con.prepareStatement("update account set ACCNAME = ?, ACCTYPE = ?, BALANCE = ? where ACCNO = ?"); pst.setString(1, accName);
   
      pst.setString(2, accType); 
      pst.setInt(3, balance); 
      pst.setString(4, accNo); 
      pst.executeUpdate(); 
      status = "success";
   } catch (Exception e) {
       status = "failure";
      e.printStackTrace(); 
   }
   return status; 
}

@Override
public String delete(String accNo) {
try {
   Connection con = dataSource.getConnection(); PreparedStatement pst = con.prepareStatement("select * from
   account where accNO = ?"); 

   pst.setString(1, accNo);
   
   ResultSet rs = pst.executeQuery(); boolean b = rs.next();
   
   if(b == true) {
      pst = con.prepareStatement("delete from account where accNo = ?");
       pst.setString(1, accNo); pst.executeUpdate(); status = "success";
   } else {
      status = "notexisted";}

}catch (Exception e) {
   status = "failure";
   e.printStackTrace(); 
}
return status; 
}
}

AccountService.java

package com.cloud.service;
import com.cloud.dto.Account;

public interface AccountService {
   public String createAccount(String accNo, String accName, String accType, int balance);
   public String searchAccount(String accNo);
   public Account getAccount(String accNo);
   public String updateAccount(String accNo, String accName, String accType, int balance);
   public String deleteAcount(String accNo); 
}

AccountServiceImpl.java

package com.cloud.service;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service;
import com.cloud.dao.AccountDao; import com.cloud.dto.Account;

@Service("accService")
public class AccountServiceImpl implements AccountService {

   @Autowired(required=true)
   private AccountDao dao;

   @Override
   public String createAccount(String accNo, String accName, String accType, int balance) {
      return dao.create(accNo, accName, accType, balance); 
   }

   @Override
   public String searchAccount(String accNo) {
      return dao.search(accNo); 
   }

   @Override
   public Account getAccount(String accNo) {
      return dao.getAccount(accNo); 
   }

   @Override
   public String updateAccount(String accNo, String accName, String accType, int balance) {
      return dao.update(accNo, accName, accType, balance); 
   }
   
   @Override
   public String deleteAcount(String accNo) {
      return dao.delete(accNo); 
   }
}

Account.java

package com.cloud.dto;
public class Account { 
   private String accNo;
   private String accName; 
   private String accType; 
   private int balance;

   public String getAccNo() {
      return accNo; 
   }

   public void setAccNo(String accNo) {
      this.accNo = accNo; 
   }

   public String getAccName() { 
      return accName;
   }

   public void setAccName(String accName) {
      this.accName = accName; 
   }

   public String getAccType() {
      return accType; 
   }

   public void setAccType(String accType) {
      this.accType = accType; 
   }

   public int getBalance() {
      return balance; 
   }

   public void setBalance(int balance) {
      this.balance = balance; 
   }
}

AccountConfig.java

package com.cloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.cloud.dao.AccountDao;
import com.cloud.dao.AccountDaoImpl; 
import com.cloud.service.AccountService; 
import com.cloud.service.AccountServiceImpl;
import oracle.jdbc.pool.OracleDataSource;

@Configuration
public class AccountConfig {

   @Bean 
   public OracleDataSource dataSource() {

      OracleDataSource dataSource = null;

      try {
       dataSource = new OracleDataSource(); 
       dataSource.setURL("jdbc:oracle:thin:@localhost:1521:xe"); 
       dataSource.setUser("system"); 
       dataSource.setPassword("cloud");
      } catch (Exception e) {
         e.printStackTrace(); 
      }
   return dataSource; 
  }

   @Bean
   public AccountService accService() {
      AccountService accService = new AccountServiceImpl();
      return accService; 
   }
   
   @Bean
   public AccountDao dao() {
      AccountDao dao = new AccountDaoImpl();
      return dao; 
   }
}

Drawbacks with Autowiring:

  • Autowiring is less exact than normal wiring.
  • Autowiring will not provide configuration metadata to the documentation tools to prepare Documentations.
  • Autowiring will increase confision when we have more than one bean object of the same type in IOC Container.
  • In Spring applications, if we provide both explicit wiring and autowiring both at a time to a bean object injection then explicit wiring overrides autowiring configurations.
  • In Spring configuration files, Explicit wiring will improve readability when compared with autowiring.
  • In Spring applications, if we have more and more no of bean objects to inject there it is suggestible to use explicit wiring when compared with autowiring.
  • Autowiring is applicable for only bean objects injection, it is not applicable for simple values injection like primitive values, string values

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS