Spring — Programmatically approach | Code Factory

Donate : Link

WordPress Blog : Link

Applications… : Link

Spring Tutorial Index Page: Link

Create Java Project

  • Open Eclipse
  • Go to File -> New -> Others… -> Java Project
  • Create BeanLifecycle project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs (Used 2.X jars)
    - commons-logging-X.X.jar
    - spring-beans-X.X.X.jar
    - spring-context-X.X.X.jar
    - spring-core-X.X.X.jar
    - mysql-connector-java-X.X.X.jar
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

spring.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="t" class="com.codeFactory.beans.Test" >
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>

Test.java

package com.codeFactory.beans;import java.sql.Connection;
import java.sql.DriverManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Test implements InitializingBean, DisposableBean { private String driver, url, username, password;
private Connection con;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void afterPropertiesSet() throws Exception {
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection: " + con + " opened");
}
@Override
public void destroy() throws Exception {
con.close();
System.out.println("Connection closed");
}
}

Client.java

package com.codeFactory.test;import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Test;/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");

Test c = (Test) context.getBean("t");
context.close();
}
}

Output:

Connection: com.mysql.cj.jdbc.ConnectionImpl@2928854b opened
Connection closed