티스토리 뷰

토비의 스프링3 교재는 아래와 같은 흐름이다.


용어정리

컨스트럭터(Constructor):'생성자'라고 보통 번역을 하지만 한자어이므로 그냥 컨스트럭터라고 쓴다.



프로젝트 생성 방법


//STS(eclipse), Maven으로 하는 경우

sts를 켠다

1.패키지 익스플로러(package explorer)에서 우측 클릭 해서 컨텍스트(context) 메뉴를 열어서 스프링 프로젝트(spring project)를 생성을 선택한다.

2.옵션은 스프링 웹 메이븐(spring web maven)이나 스프링 엠브이씨(spring mvc)를 선택한다.

3.생성한 프로젝트에 우클릭을 해서 메이븐 클린(maven clean)을 한다.

4.메이븐 인스톨(maven install)을 한다.

5.pom에서 com.mysql.jdbc.driver 를 디펜던씨(dependency)에 추가한다.

6.메이븐 클린 - 메이븐 인스톨 한다.



//Intelli J, Gradle로 하는 경우


build.gradle

apply plugin: 'java'
apply plugin: 'idea'


sourceCompatibility = 1.5
version = '1.0'

repositories {
mavenCentral()
}

dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'mysql:mysql-connector-java:5.1.6'

}




리팩토링 순서

1.User, UserDao만든다


User.java

/**

* Created by krkim on 2015-09-08.
*/
public class User {
String id;
String password;
String name;

public User() {
}

public User(String id, String password, String name) {
this.id = id;
this.password = password;
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


UserDao.java

import java.sql.*;

/**
* Created by krkim on 2015-09-08.
*/
public class UserDao {

private Connection getConnection() throws ClassNotFoundException, SQLException {

Class.forName("com.mysql.jdbc.Driver");

Connection c = DriverManager.getConnection(
"jdbc:mysql://localhost/krkdb",
"root",
"111111"
);


return c;
}

public void add(User user) throws SQLException {
Connection c = null;

try {
c = getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

PreparedStatement ps = c.prepareStatement("insert into users(id, password, name) values(?,?,?)");
ps.setString(1, user.getId());
ps.setString(2, user.getPassword());
ps.setString(3, user.getName());

ps.executeUpdate();

ps.close();
c.close();

}

public User get(String id) throws SQLException {
Connection c = null;

try {
c = getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

PreparedStatement ps = c.prepareStatement("select * from users where id=?");
ps.setString(1, id);

ResultSet rs = ps.executeQuery();
rs.next();

User user = new User(rs.getString("id"), rs.getString("password"), rs.getString("name") );

rs.close();
ps.close();
c.close();

return user;
}

}


2.getConnection()을 분리한다.

위에서 했음


3.추상 클래스 이용해서 connection 개별 구현하기

이건 안쓰기 때문에 넘어감


4.인터페이스 이용해서 개별 connection만들기

아래에서 같이 할 예정


5.전략 패턴 이용

2015/09/08 - [Web개발/Spring] - Toby의 Spring3 따라하기-제3편 connectionMaker interface 이용해서 분리하기



6.팩토리 메소드 패턴 이용



7.application context로 리팩토링 하면서 싱클톤 패턴 구현

spring library를 import 한다.


applicationContext.xml은 src/main/resource에 넣는다.

applicationContext.xml은 클라이언트(Client)역할을 하는 UserDaoTest에서 불러온다.


Test code에서 dao를 ApplicationContext를 이용해 생성한다.


applicationContext.xml을 작성하다보면 에러가 나는데 spring-jdbc가 없어서 나는 에러이다. pom.xml에서 spring-jdbc 디펜던씨(dependency)를 추가 해준다.


applicationContext를 이용해 userDao 오브젝트(object)를 받아올 수 있는데 해당 userDao 오브젝트는 dataSource object가 DI된 상태이다. 이 정보가 applicationContext.xml에 기록이 되어있다.





막히는 부분에 대한 간단한 설명

dataSource object에서 getConnection() 메소드를 이용해 connection Object를 생성할 수 있다.


1장의 내용은 userDao에 dataSource를 글로벌 변수로 선언하는 것으로 마무리 된다.


dataSource object를 전역 변수로 선언해 놓으면 dataSource는 DI받으면 되므로 connection에 관해 더이상 신경쓰지 않아도 되는 코드를 만들 수 있다.


외부에서 object를 넣어주는 방법(토비는 주입 이라고 써놓았다)을 DI라고 하는데 DI하는 방법은 컨스트럭터를 이용하는 방법과 셋 메소드를 이용하는 방법 두가지가 있다.









공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함