본문 바로가기
java/spring

spring - mysql 연결(2)

by rewind 2024. 7. 9.

클래스파일에 직접 설정해서 않고 root-context.xml 파일에 빈객체 작성해서 연결해본다. 먼저 root-context.xml 파일에 드라이버 정보를 작성

root-context.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/springbasic?useUnicode=true&amp;characterEncoding=utf8"></property>
    <property name="username" value="callipix"></property>
    <property name="password" value="java"></property>
</bean>

 

연결 클래스 생성

public class DBConnectionTest2 {	
	public static void main(String[] args) throws Exception {
		
    ApplicationContext ac = new GenericXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/**/root-context.xml");
    // 1.GenericXmlApplicationContext 클래스를 사용해서 Spring ApplicationContext를 초기화
    // 매개변수로 설정파일의 경로를 지정 → root-context.xml 파일을 포함하는 모든 경로에서 파일(빈)을 로드

    DataSource ds = ac.getBean(DataSource.class);
    // 2.DataSource는 DB연결을 관리하는 객체로 root-context.xml 파일에서 정의되어 있어야 한다. 
    // ac의 getBean메소드로 DataSource타입 빈을 ApplicationContext에서 가져온다

    Connection conn = ds.getConnection();		
    // 3.ds객체의 getConnection메소드로 DB연결 객체를 가져온다
    // 이 연결객체를 통해 DB와 연결하게 된다
    System.out.println("conn = " + conn);
	}
}

 

이러고 실행하면 이런 오류가 뜨면서 안된다

INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from file [C:\STS3\proj_work\ch2\src\main\webapp\WEB-INF\spring\root-context.xml]
INFO : org.springframework.context.support.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@770c2e6b: startup date [Tue Jul 09 20:18:59 KST 2024]; root of context hierarchy
WARN : org.springframework.context.support.GenericXmlApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in file [C:\STS3\proj_work\ch2\src\main\webapp\WEB-INF\spring\root-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in file [C:\STS3\proj_work\ch2\src\main\webapp\WEB-INF\spring\root-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1380)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:668)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:635)
	at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489)
	at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1012)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:740)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
	at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:71)
	at com.fastcampus.ch3.DBConnectionTest2.main(DBConnectionTest2.java:14)
Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
	at org.springframework.util.ClassUtils.forName(ClassUtils.java:274)
	at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:437)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1428)
	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1372)
	... 9 more

 

이유는 위에서 연결을 관리해주는 DataSource가 있어야 하는데 없어서.. org.springframework.jdbc.datasource.DriverManagerDataSource 경로에 DataSource 객체가 있어야 하는데 해당 클래스를 찾을 수 없다는 얘기이다. 메이븐에 JDBC dependency 추가를 안했으니까 추가한뒤 메이븐 업데이트를 하고 다시 실행해본다

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

 

잘 실행된다