Spring DI

The following article assumes that your workspace is C:\java.

Set up the project

Execute the following command in C:\java.
(↵ is an indication to press the enter key, just press the enter key to select the default value)

C:\ Command Prompt
C:\java>mvn archetype:generate

Choose a number or apply filter 
    (format: [groupId:]artifactId, case sensitive contains): 888: ↵

Choose org.apache.maven.archetypes:maven-archetype-quickstart version: 
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1
Choose a number: 6: ↵
Define value for property 'groupId': : net.java_school
Define value for property 'artifactId': : bank
Define value for property 'version':  1.0-SNAPSHOT: : ↵
Define value for property 'package':  net.java_school: : ↵
Confirm properties configuration:
groupId: net.java_school
artifactId: bank
version: 1.0-SNAPSHOT
package: net.java_school
 Y: : ↵

Access the scott account with SQL * PLUS.
Create the following table.

create table bankaccount (
    accountno varchar2(50),
    owner varchar2(20) not null,
    balance number,
    kind varchar2(10),
    constraint PK_BANKACCOUNT primary key(accountno),
    constraint CK_BANKACCOUNT_NORMAL 
        CHECK (balance >= CASE WHEN kind='NORMAL' THEN 0 END),
    constraint CK_BANKACCOUNT_KIND CHECK (kind in ('NORMAL', 'MINUS'))
);  
create table transaction (
    transactiondate timestamp,
    kind varchar2(10),
    amount number,
    balance number,
    accountno varchar2(50),
    constraint FK_TRANSACTION FOREIGN KEY(accountno)
        REFERENCES bankaccount(accountno)
);

Create a trigger that inserts data into a transaction table when depositing or withdrawing.

create or replace trigger bank_trigger
after insert or update of balance on bankaccount
for each row
begin
    if :new.balance > :old.balance then
        insert into transaction 
        values 
        (
            systimestamp,
            'DEPOSIT',
            :new.balance - :old.balance,
            :new.balance,
            :old.accountno
        );
    end if;
    if :new.balance < :old.balance then
        insert into transaction 
        values 
        (
            systimestamp,
            'WITHDRAW',
            :old.balance - :new.balance,
            :new.balance,
            :old.accountno
        );
    end if;
end;
/

Copy https://github.com/kimjonghoon/JavaBank sources and paste them to the following locations:

C:\java\bank
   └── src
        └── main
             └── java
                  └── net
                       └── java_school
                               └── bank
                                        - Account.java
                                        - Bank.java
                                        - BankDao.java
                                        - BankUi.java
                                        - ShinhanBank.java
                                        - ShinhanBankDao.java
                                        - Transaction.java

Installing the Oracle JDBC driver in local repository

The Oracle JDBC driver is not provided by the Maven repository.
Therefore, you need to install the Oracle JDBC driver in your local repository and set the dependency on pom.xml.
Go to the directory where the ojdbc6.jar file is located, and run the following from the command prompt:

mvn install:install-file -Dfile=ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.2.0 -Dpackaging=jar

Add the following dependencies to pom.xml as the information is stored in the local repository:

<dependency>
	<groupId>com.oracle</groupId>
	<artifactId>ojdbc6</artifactId>
	<version>11.2.0.2.0</version>
</dependency>

Edit pom.xml as shown below.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                        http://maven.apache.org/xsd/maven-4.0.0.xsd">
                        
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.java_school</groupId>
  <artifactId>bank</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>bank</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.2.1.RELEASE</spring.version>
    <jdk.version>11</jdk.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.28</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.2.0</version>
    </dependency>
  </dependencies>
  
  <build>
    <finalName>bank</finalName>
      <pluginManagement>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
              <source>${jdk.version}</source>
              <target>${jdk.version}</target>
              <compilerArgument></compilerArgument>
              <encoding>UTF-8</encoding>
            </configuration>
          </plugin>
        </plugins>
      </pluginManagement>
  </build>
  
</project>

Build and run.

C:\ Command Prompt
C:\java\bank>mvn clean compile

C:\java\bank>mvn exec:java -Dexec.mainClass=net.java_school.bank.BankUi

Migrating to Spring project

Modify the following:

Bank.java
public void setDao(BankDao dao);//added
ShinahanBank.java
//private BankDao dao = new ShinhanBankDao();

//added
private BankDao dao;

public void setDao(BankDao dao) {
    this.dao = dao;
}
BankUi.java
//..omit..

import java.io.PrintStream;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//..omit..
//private Bank bank = new ShinhanBank();
private Bank bank;

public void setBank(Bank bank) {
    this.bank = bank;
}

private PrintStream stream;

public void setStream(PrintStream stream) {
    this.stream = stream;
}

/* 
Modify System.out.println() to stream.println(), System.out.println() to stream.println().
*/

//..omit..

public static void main(String[] args) {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
	BankUi ui = ctx.getBean(BankUi.class);
	ui.startWork();
	ctx.close();
}

Create src/main/resources folder. (This is also the Maven project directory)
Copy logback.xml in Logging and paste it into resources folder.
Create an applicationContext.xml in the resources folder.

C:\java\bank
   └── src
        └── main
             └── resources
                           - logback.xml
                           - applicationContext.xml
                     

Edit the appliactionContext.xml file as follows.

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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="bankUi" class="net.java_school.bank.BankUi">
        <property name="stream" value="#{T(System).out}" />
        <property name="bank" ref="shinhanBank" />
    </bean>
    
    <bean id="shinhanBank" class="net.java_school.bank.ShinhanBank">
        <property name="dao" ref="shinhanBankDao" />
    </bean>

    <bean id="shinhanBankDao" class="net.java_school.bank.ShinhanBankDao">
    </bean>

</beans>

Build and run.

C:\ Command Prompt
C:\java\bank>mvn clean compile

C:\java\bank>mvn exec:java -Dexec.mainClass=net.java_school.bank.BankUi

Set up the project in Eclipse

Start Eclipse. (It does not matter where your workspace is)
In the Project Explorer view, use the right mouse button to display the context menu.
Import the JavaBank project into Eclipse as shown below.
Open Import menu in context menu
Import the JavaBank project
Synchronize Eclipse with pom.xml as follows.
With the project selected in the Package Explorer, open the context menu with the right mouse button.
Select Maven, then Update Project Configuration.

If pom.xml changes afterwards, you should synchronize with Eclipse.

JavaConfig

It is now possible to make bean settings with Java classes instead of XML files nowdays. You can write a bean configuration class that uses @Configuration and @Bean annotations. In a bean configuration class, the method name annotated with @Bean becomes an bean object.

To test the bean configuration class, comment out all settings in applicationContext.xml.

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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 
    <bean id="bankUi" class="net.java_school.bank.BankUi">
        <property name="stream" value="#{T(System).out}" />
        <property name="bank" ref="shinhanBank" />
    </bean>
    
    <bean id="shinhanBank" class="net.java_school.bank.ShinhanBank">
        <property name="dao" ref="shinhanBankDao" />
    </bean>

    <bean id="shinhanBankDao" class="net.java_school.bank.ShinhanBankDao">
    </bean>
-->
</beans>

Create the bean configuration class as follows:

BankConfig.java
package net.java_school.bank;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BankConfig {
	
	@Bean
	public BankDao shinhanBankDao() {
		return new ShinhanBankDao();
	}
	
	@Bean
	public Bank shinhanBank() {
		Bank bank = new ShinhanBank();
		bank.setDao(shinhanBankDao());
		return bank;
	}
	
	@Bean
	public BankUi bankUi() {
		BankUi ui = new BankUi();
		ui.setBank(shinhanBank());
		ui.setStream(System.out);
		return ui;
	}
	
}

Modify the main method of the BankUi class as shown below.

BankUi.java
//the following import statement is added
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

//..omit..

public static void main(String[] args) {
	//ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BankConfig.class);
	BankUi ui = ctx.getBean(BankUi.class);
	ui.startWork();
	ctx.close();
}

Final Source : https://github.com/kimjonghoon/di

References