Spring Simple JDBC 예제
1. EmpDao.java
package jdbc1;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmpDao {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
List getNames() {
return jdbcTemplate.queryForList("select * from emp where rownum < 2");
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
}
2. JdbcTestClient.java
package jdbc1;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class JdbcTestClient {
public static void main(String[] args) {
XmlBeanFactory ctx = new XmlBeanFactory( new FileSystemResource("C:\\java\\Tomcat 5.5\\webapps\\SpringAOP\\jdbc1\\jdbc.xml"));
EmpDao dStuff = (EmpDao) ctx.getBean("EmpDao");
System.out.println(dStuff.getNames());
ctx.destroySingletons();
}
}
3. Jdbc.xml
<!-- commons-collection.jar, commons-dbcp.jsr, commons-pool.jar 필요함 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="EmpDao" class="jdbc1.EmpDao">
<property name="dataSource"><ref local="dataSource"/></property>
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:wink</value>
</property>
<property name="username">
<value>scott</value>
</property>
<property name="password">
<value>tiger</value>
</property>
</bean>
</beans>
4. 결과
2008. 5. 8 오후 9:11:10 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
정보: Loading XML bean definitions from file [C:\java\Tomcat 5.5\webapps\SpringAOP\jdbc1\jdbc.xml]
[{EMPNO=7369, ENAME=SMITH, JOB=CLERK, MGR=7902, HIREDATE=1980-12-17 00:00:00.0, SAL=800, COMM=null, DEPTNO=20}]
2008. 5. 8 오후 9:11:12 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
정보: Destroying singletons in org.springframework.beans.factory.xml.XmlBeanFactory@1198891: defining beans [EmpDao,dataSource]; root of factory hierarchy
댓글 없음:
댓글 쓰기