This example presents the basic concept of configuring Datasource in Spring JDBC.
The technologies used are :
-
– Spring 4.3.18
– H2 1.3
– Lombok 1.18
– JDK 1.80
– Maven 3.3.9
You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :
mvn eclipse:eclipse
Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).
<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>javaspringexamples.springJDBC</groupId> <artifactId>springJdbcConfiguringDatasource</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.175</version> </dependency> </dependencies> </project>
package javaspringexamples.springJDBC.Datasource; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * * @author mounir.sahrani@gmail.com * */ @Configuration public class AppConfiguration { @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:tcp://localhost/~/javaspringexamples"); dataSource.setUsername("sa"); dataSource.setPassword(""); return dataSource; } }
package javaspringexamples.springJDBC.Datasource; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * * @author mounir.sahrani@gmail.com * */ public class Main { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( AppConfiguration.class); DataSource dataSource = applicationContext.getBean("dataSource", DataSource.class); Connection connection = dataSource.getConnection(); System.out.println(connection.isClosed()); connection.close(); System.out.println(connection.isClosed()); } }
Get the sources of the example from the following GitHub url