Actuator
- 실행중인 Spring Boot 애플리케이션의 정보를 API 형식으로 확인할 수 있게 해주는 기능 (실행 중에만 가능)
1) 의존성 추가
- Spring Starter Project를 생성할 때 Spring Boot Actuator 의존성을 추가할 수 있다
- 또는 pom.xml 에서 직접 의존성을 추가할 수 있다
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2) Actuator 활성화 설정
- Boot Dashboard에서 프로젝트의 Show Properties 정보 중 Request Mappings, Beans, Env(Environment)를 활성화
** Actuator를 활성화하지 않은 경우
- application.properties 에서 mapping, beans, env에 대한 정보를 활성화
- Actuator 활성화 후 Boot Dashboard에서 프로젝트의 Show Properties
Spring Boot JDBC를 사용하여 Oracle DB 연동
1) Spring Starter Project에서 의존성 추가
- 기존의 Spring Boot Devtools, Spring Boot Web, Spring Boot Actuator 외에 Oracle Driver, JDBC API를 추가한다
** 추가된 의존성 확인
- spring-boot-starter-jdbc와 ojdbc8이 추가된 것을 알 수 있다
2) application.properties 설정 (띄어쓰기 없이 작성)
- 기존에 작성했던 port 번호 변경, actuator 설정 외에 jdbc 연결 정보를 추가한다
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver | DB 드라이버 클래스 이름 설정 |
pring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe | DB 접속 주소 설정 |
spring.datasource.username=khacademy | 사용자 이름 설정 |
spring.datasource.password=khacademy | 사용자 비밀번호 설정 |
3) DTO 생성 - CRUD 중 조회 명령을 위해 미리 생성해둔다
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
public class PocketMonsterDto {
// 필드 - DB의 컬럼 타입과 일치하도록
private int no;
private String name;
private String type;
// 생성자
public PocketMonsterDto() {
super();
}
// setter & getter
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
// toString 오버리이딩
@Override
public String toString() {
return "PocketMonsterDto [no=" + no + ", name=" + name + ", type=" + type + "]";
}
// RowMapper의 인스턴스 생성
private static RowMapper<PocketMonsterDto> mapper = (rs, idx) -> {
PocketMonsterDto dto = new PocketMonsterDto();
dto.setNo(rs.getInt("no"));
dto.setName(rs.getString("name"));
dto.setType(rs.getString("type"));
return dto;
};
// RowMapper에 대한 getter - RowMapper의 인스턴스 mapper 반환 메소드
public static RowMapper<PocketMonsterDto> getMapper() {
return mapper;
}
// ResultSetExtractor의 인스턴스 생성
private static ResultSetExtractor<PocketMonsterDto> extractor = (rs) -> {
if(rs.next()) {
PocketMonsterDto dto = new PocketMonsterDto();
dto.setNo(rs.getInt("no"));
dto.setName(rs.getString("name"));
dto.setType(rs.getString("type"));
return dto;
}
else {
return null;
}
};
// ResultSetExtractor에 대한 getter - ResultSetExtractor의 인스턴스 extractor 반환 메소드
public static ResultSetExtractor<PocketMonsterDto> getExtractor() {
return extractor;
}
}
3) Controller 클래스 생성
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.kh.spring06.entity.PocketMonsterDto;
@Controller
@RequestMapping("/pocket-monster")
public class PocketMonsterController {
// 1. JdbcTemplate의 인스턴스 생성 (@Autowired에 의한 의존성 객체 주입)
@Autowired
private JdbcTemplate jdbcTemplate;
// 입력(insert)
@RequestMapping("/insert") // 접속 주소 mapping
// 응답 본문에는 해당 요청 파라미터를 매개변수로 하여 insert() 메소드 실행 후 String 반환
@ResponseBody
public String insert(@RequestParam int no, @RequestParam String name, @RequestParam String type) {
// 2. SQL문 작성
String sql = "insert into pocket_monster(no, name, type) values(?, ?, ?)";
// 3. 변수 배열 생성
Object[] param = new Object[] {no, name, type};
// 4. SQL문 전송 및 실행
jdbcTemplate.update(sql, param);
// 5. 실행 후 "등록 완료"라는 문자열을 반환
return "등록 완료!";
}
// 포켓몬 입력(insert)에 대한 접속 주소
// http://localhost:8888/pocket-monster/insert?no=5&name=리자드&type=불꽃
// 수정(update) - 번호(no)를 이용해서 이름(name)과 유형(type) 변경
@RequestMapping("/update")
// 응답 본문에는 해당 요청 파라미터를 매개변수로 하여 update() 메소드 실행 후 String 반환
@ResponseBody
public String update(@RequestParam int no, @RequestParam String name, @RequestParam String type) {
// 2. SQL문 작성
String sql = "update pocket_monster set name = ?, type = ? where no = ?";
// 3. 변수 배열 생성
Object[] param = new Object[] {name, type, no};
// 4. SQL문 전송 및 실행
int result = jdbcTemplate.update(sql, param);
// 5. 실행 후 문자열 반환
if(result > 0) { // 바뀐 레코드 수가 0 이상이면 "등록 완료"라는 문자열을 반환
return "수정 완료!";
}
else { // 그렇지 않으면 "없는 번호"라는 문자열을 반환
return "없는 번호";
}
}
// 포켓몬 수정(update)에 대한 접속 주소
// http://localhost:8888/pocket-monster/update?no=5&name=꼬부기&type=물
// 삭제(delete) - 번호(no)를 이용해서 삭제
@RequestMapping("/delete")
// 응답 본문에는 해당 요청 파라미터를 매개변수로 하여 update() 메소드 실행 후 String 반환
@ResponseBody
public String delete(@RequestParam int no) {
// 2. SQL문 작성
String sql = "delete pocket_monster where no = ?";
// 3. 변수 배열 생성
Object[] param = new Object[] {no};
// 4. SQL문 전송 및 실행
int result = jdbcTemplate.update(sql, param);
if(result > 0) { // 바뀐 레코드 수가 0 이상이면 "등록 완료"라는 문자열을 반환
return "삭제 완료!";
}
else { // 그렇지 않으면 "없는 번호"라는 문자열을 반환
return "없는 번호";
}
}
// 포켓몬 삭제(delete)에 대한 접속 주소
// http://localhost:8888/pocket-monster/delete?no=5
// 4. 조회(select)
@RequestMapping("/select")
// 응답 본문에는 select() 메소드 실행 후 String 반환
// PocketMonster 타입 인스턴스 dto가 저장된 List의 정보를 StringBuffer를 통해 문자열로 반환
@ResponseBody
public String select() {
// 2. SQL문 작성
String sql = "select * from pocket_monster order by no asc";
// 3. 변수 배열 생성 - 전체 조회(select)이므로 변수는 필요 없다
// 4. SQL문 전송 및 실행 후 PocketMonsterDto 타입의 ResultSet을 List에 저장
List<PocketMonsterDto> list = jdbcTemplate.query(sql, PocketMonsterDto.getMapper());
// StringBuffer로 문자열을 이어붙여 List 구성 요소의 정보를 반환
StringBuffer buffer = new StringBuffer();
for(PocketMonsterDto dto : list) {
buffer.append(dto);
buffer.append("<br>");
}
return buffer.toString();
}
// 포켓몬 조회(select)에 대한 접속 주소
// http://localhost:8888/pocket-monster/select
// 5. 단일 조회(detail)
@RequestMapping("/detail")
@ResponseBody
public String detail(@RequestParam int no) {
String sql = "select * from pocket_monster where no = ?";
Object[] param = {no};
PocketMonsterDto dto = jdbcTemplate.query(sql, PocketMonsterDto.getExtractor(), param);
if(dto == null) {
return "없는 번호";
}
else {
return dto.toString();
}
}
// http://localhost:8888/pocket-monster/detail?no=1
}
JdbcTemplate의 인스턴스 생성 (의존성 주입, DI)
- @Autowired는 등록된 Spring bean 중에서 해당 자료형 혹은 해당 자료형의 하위 자료형을 찾아
의존성 주입(DI, Dependency Injectiopn) 처리하는 명령이다.
@Autowired | 등록된 Spring bean 중에서 해당 자료형 혹은 그 하위 자료형을 찾아 의존성 주입 처리 |
spring09quiz 까지
'국비교육 > 국비교육' 카테고리의 다른 글
day28 - 0901 (0) | 2022.09.01 |
---|---|
day27 - 0831 (0) | 2022.08.31 |
day25 - 0829 (0) | 2022.08.30 |
day24 - 0826 (0) | 2022.08.27 |
day23 - 0825 (0) | 2022.08.27 |