반응형

[1] 빌드하고 실행하기

사전작업 : spring 프로젝트를 생성한 상태. IDEL 에서 run 하여 포트연결이 확인 된 상태

// gradlew 파일이 위치한 곳으로 이동
> ll
build.gradle
gradle
gradlew
gradlew.bat
settings.gradle
src
// 아래 명령어 입력
> ./gradlew build
BUILD SUCCESSFUL in 4s
// 그러면 해당 경로에 build 폴더가 생성된다. build 파일 하위의 libs 폴더로 이동한다
> cd build/libs
> ll
staff   2.7K  4 21 22:42 hello-spring-0.0.1-SNAPSHOT-plain.jar
staff    20M  4 21 22:42 hello-spring-0.0.1-SNAPSHOT.jar
// 왜 -plain 이라는 jar 파일이 있는지는 모르겠음.... 일단 생성된 jar 파일을 실행시킨다
> java -jar hello-spring-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.4)
INFO 2389 --- [hello-spring] [           main] j.hellospring.HelloSpringApplication     : Started HelloSpringApplication in 1.823 seconds (process running for 2.374)

서버에서 프로젝트를 실행하려고 하면 jar 파일을 생성하여 서버에 올리고, 서버에서 jar 파일을 실행하도록 하면 된다.

만약 빌드가 제대로 이뤄지지 않은 경우 build 폴더를 삭제하고 다시 빌드해본다.

// 기존에 생성된 build 폴더를 삭제한다.
$ ./gradlew clean

// 이후 재 빌드한다.
$ ./gradlew build

// clean 과 빌드를 동시에 한다 (clean 후 빌드)
$ ./gradlew clean build

[2] DI 와 스프링 빈 등록하기

- DI (Dependency Injection , 의존성 주입)

DI를 사용하면 기존 코드를 전혀 손대지 않고, 설정만으로 구현 클래스를 변경할 수 있다.

예) Repository Interface를 Service에서 사용하고 해당 인터페이스를 implement한 구현체를 A 에서 B로 바꾸면 DB설계가 변경되었는 상황에서 오직 Repository 만 새로 작성하고 다른 기존 코드는 수정하지 않아도 된다.

> @Controller @Service @Repository

// controller
@Controller
public class AContoller{
    private final AService aService;

    @Autowired // Autowired 해놓으면 컴파일 될때 해당 객체를 가져온다
    public AController(AService aService) {
        this.aService = aService;
    }   
}

// service
@Service
public class AService {
    private final ARepository aRepository;

    @Autowired
    public AService(ARepository aRepository) {
        this.aRepository = aRepository;
    }

// repository
@Repository
public class ARepository {
}

? 만약 @Service annotation이 붙어있지 않다면

Parameter 0 of constructor in hellospring.controller.AController required a bean of type 'hellospring.service.AService' that could not be found.

해당 에러가 발생한다. AService 라는 bean이 필요한데 찾을수 없다는 뜻. 따라서 annotation을 붙여주어 service 를 지정해준다.

> DI의 3가지 방법 : 필드 주입, setter 주입, 생성자 주입

1] 필드 주입

임의 조작이 불가능 하여 intelliJ에서는 변경을 권고한다. (노란줄 표시)

@Controller
public class AContoller{
    @Autowired private final AService aService;
}

2] setter 주입

command + N 으로 setter 생성

단점 : 누군가가 AController를 호출할때 serAService가 public 으로 호출되어 보안상 권고되지 않는다. (변경할수있게 되는 상태)

@Controller
public class AController {
    private AService aService;

    @Autowired
    public void setAService(AService aService) {
        this.aService = aService;
    }
}

3] 생성자 주입

- 위 예제에서 주입한 방법

- 가장 권장되는 방식

@Controller
public class AContoller{
    private final AService aService;

    @Autowired
    public AController(AService aService) {
        this.aService = aService;
    }   
}

- Spring bean을 등록하는 2가지 방법

1] 컴포넌트 스캔과 자동 의존관계 설정

- @Component 어노테이션을 사용하는 방법이 있다.

- 실행하는 어플리케이션과 동일한 package 이거나, 하위 package에 등록된 component만 spring bean으로 등록한다.

2] java 코드로 직접 스프링 빈 등록하기

실행 어플리케이션과 동일한 package 경로에 config 파일을 생성해 준다.

@Configuration
public class SpringConfig {
    @Bean
    public AService aService() {
        return new AService(aRepository());
    }

    @Bean
    public ARepository aRepository() {
        return new aRepository();
    }
}

위 코드를 작성하면 어플리케이션이 실행될때 @Configuration 어노테이션에 따라 @Bean으로 지정된 것들을 생성한다.

이전에 작성한 @Service와 @Repository 를 해제하고, @Service에서 @Autowired한것도 지웠을때 어플리케이션을 실행하면 정상적으로 실행된다.

// controller
@Controller
public class AContoller{
    private final AService aService;

    @Autowired // Autowired 해놓으면 컴파일 될때 해당 객체를 가져온다
    public AController(AService aService) {
        this.aService = aService;
    }   
}

// service
public class AService {
    private final ARepository aRepository;

    public AService(ARepository aRepository) {
        this.aRepository = aRepository;
    }

// repository
public class ARepository {
}

만약 위 config를 설정하지 않고 어노테이션만 지운 뒤 실행하면 필요한 bean을 찾지 못한다는 에러가 발생한다.

위 방법을 사용하면 repository 가 변경되었을때 (연결 DB 종류가 바뀐다던가..), config 파일에서 등록될 bean 부분만 코드를 수정해 주면 된다.

 

[3] 스프링 과 DB

1] h2

> homebrew 로 설치하기

참고로.. intel 맥북에어 메모리 8gb 스펙에서 brew 로 h2 다운로드 받으면 1시간걸린다...

brew install h2

 

> h2 실행하기

h2가 설치된 경로에 들어가서 h2 파일이 있는곳에서 접근권한을 부여해 주어야 한다.

// h2 > h2 > bin
chmod 755 h2.sh

이후 build.gradle 파일에 jdbc, h2 데이터베이스 관련 라이브러리 추가

- 단위테스트와 통합테스트

- 순수 java 코드로만 테스트 작성 : 단위 테스트

- Spring application 이 실행되는 테스트 : 통합테스트

 

단위테스트를 우선적으로 작성할 줄 알면 좋다~!

 

- JPA

스프링 데이터 JPA 를 활용해 기본제공 쿼리 사용하여 코드를 간단하게 구현할수 있다.

 

[4] AOP

AOP가 필요한 때 예시

- 모든 메소드의 호출 시간을 측정하고 싶다면?
- 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern)

- 회원 가입 시간, 회원 조회 시간을 측정하고 싶다면?

 

 

- AOP: Aspect Oriented Programming

공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern) 분리

@Aspect 를 활용한다.

반응형

+ Recent posts