[JDBC/MySQL] XML로 JDBC 다뤄보기 (3)

Dev.Hammy·2024년 3월 12일
0

Etc

목록 보기
18/20

XML 파일의 설정 내용을 Java Config로 전환해보기

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="url" value="jdbc:mysql://localhost:3306/School" />
        <property name="username" value="사용자이름" />
        <property name="password" value="비밀번호" />
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />

    </bean>

    <bean id="jdbcTemplateObject" class="org.springframework.jdbc.core.JdbcTemplate">

        <constructor-arg name="dataSource" ref="dataSource" />

    </bean>

    <bean id="studentDao" class="tutorial.schooljdbc.StudentDAOImpl">
        <property name="jdbcTemplate" ref="jdbcTemplateObject"> </property>
    </bean>

</beans>

지난 게시물에서 작성한 beans.xml의 최종 모습은 위와 같습니다. 이것을 다시 차례대로 자바 어노테이션 방식으로 전환해보겠습니다.

위와 같이 studentDao 빈을 주석처리 합니다. 이 상태에서 Poulate 클래스의 main 함수를 실행하면 application context는 로드되지만 빈 정의 파일을 찾을 수 없어 에러가 발생합니다.

그렇다면 어떻게 context에 studentDaoImpl 객체를 연결할 수 있을까요?

@Component / @Repository

스프링 컨테이너에게 SpringDaoImpl 클래스를 빈으로 등록하게 하려면 @Component 어노테이션을 사용해야 합니다.

또한 이 객체는 데이터베이스와의 상호작용 및 그 함수를 담게 될 예정이므로 @Repository로 특정하는 것이 좋습니다.

그리고 아래와 같이 xml 파일을 작성하여 우리가 component scan을 사용할 것이라 알립니다.

    <context:component-scan base-package="tutorial.schooljdbc"> </context:component-scan>

@Autowired

StudentDAOImpl 클래스에는 setter 방식으로 구현된 jdbcTemplate 코드가 있지만 우리가 앞서 xml에서 studentDao 빈을 주석처리 했기 때문에 xml 파일의 jdbcTemplateObject를 자바 코드에 주입하기 위해서는 @Autowired 어노테이션을 사용하도록 합니다.

어노테이션 기반 빈 이름 붙이기

StudentDAOImpl studentDAOImpl = context.getBean("studentDao", StudentDAOImpl.class);

Populate 클래스의 내부에서 컨텍스트로부터 studentDAOImpl 객체를 불러오는데 getBean을 이용하고 있습니다. 그때 이름으로 "studentDao" 를 지정하고 있지만 그 이름은 xml 파일에서 이미 주석처리 된 상태입니다.

StudentDAOImpl 클래스를 빈으로 활용할 때 부를 이름을 어노테이션 옆에 특정해줍니다.

xml 파일에 Schema Location 추가하기

<beans xmlns="http://www.springframework.org/schema/beans"
             
   xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="tutorial.schooljdbc"/>

jdbc는 schema Location을 특정해주지 않아도 문제가 없었지만 context는 java 어노테이션과 상호작용 하기 위해 Location 지정이 필요합니다.

@Repository, @Autowired가 기능하여 테이블에 새 데이터가 추가되었습니다.

0개의 댓글