본문 바로가기

SPRING

[Spring] DataSource 이용

728x90

DataSource

  • DB와 관계된 커넥션 정보를 담고있으며 빈으로 등록하여 인자로 넘겨준다.
  • → 이 과정을 통해 Spring은 DataSource로 DB와의 연결을 획득한다
  • DB 서버와의 연결을 해준다.
  • DB Connetion pooling기능
  • 위치변경시 재배포 컴파일 .. 불합당 -->dispatcher-servlet.xml
  •  
DAO커넥션이
//Class.forName(driver);
//Connection con = DriverManager.getConnection(Url,Id,Password);
이런식으로 되어있다면

Connection con = dataSource.getConnection();
이렇게 바꿈​

 

 

1) DAO

//private String Url = "";
//private String Id = "";
//private String Password = "";
//private String Driver = "";

를 => 위 4개의 정보를 담고 있는 DataSource로 변환

@Autowired
private DataSource dataSource;

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

 

2) 서블릿.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
       
      <!-- 어노테이션 사용하기위함 -->  
     <context:annotation-config/>

	<!-- class="패키지명.클래스명" -->
	<bean id="noticeService" class="com.newlecture.web.service.jdbc.JDBCNoticeService" >
	<!-- <property name="dataSource" ref="dataSource"></property> -->
	</bean>
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521/xepdb1"/>
		<property name="username" value="NEWLEC"/>
		<property name="password" value="11111"/>
	</bean>
	

</beans>

 

- DAO에 @Autowired를 쓴다면

<!-- <property name="dataSource" ref="dataSource"></property> --> 생략

<context:annotation-config/> 사용

 

id="매개변수", class="패키지명.클래스명"

​property의 name은 Datasource에서 사용하는 이름으로 입력

728x90