BackEnd/Spring

Spring_Day5_SpringLifeCycle

Leo.K 2022. 7. 11. 00:24
  • Life Cycle
    • = 생명주기, 생애주기
    • = 시작부터 끝까지
    • 스프링 컨테이너의 생명주기
      • 스프링 컨테이너 생성
      • 스프링 컨테이너 설정
      • 스프링 컨테이너 사용
      • 스프링 컨테이너 종료
  • Bean Life Cycle 관리방법
    • 인터페이스를 통한 구현(지정된 메서드명을 사용해야 한다. 스프링에서만 사용가능하다.) 
    • Bean 정의 시 메소드 지정(내가 원하는 메서드명을 사용할 수 있다. 스프링에서만 사용가능하다.) 
    • 어노테이션 지정(스프링이 아닌 컨테이너에서도 사용가능하다.) 
    • 세 가지의 경우의 수를 하나의 클래스에서 사용하지는 않겠지만 만약 그렇다면 어노테이션 -> 인터페이스 -> 메소드 지정 순서로 실행된다.
  • 어플리케이션 설계와 프로젝트 특성에 맞게 사용

[ AOP가 적용된 어플리케이션 구현 방식 ]

[ AOP 용어 ]

  • Advice: 부가 기능을 담은 모듈로 공통 로직을 담고 있는 코드
  • Joinpoint: Advice를 적용 가능한 지점
    • Spring AOP에서는 각 객체의 메소드
  • Pointcut: Joinpoint를 선별하는 기능을 정의한 모듈
  • Target: 대상 메소드를 가지는 객체
  • Proxy: Advice가 적용되었을 때 만들어지는 객체
  • Weaving: Advice를 핵심로직코드에 적용하는 것

 

[ 실습 ]

[ 스프링 컨테이너의 라이프 사이클 ]

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
31
//Student.java
private String name;
 
public String getName() {
    return name;
}
 
public void setName(String name) {
    this.name = name;
}
 
//beans.xml
<bean id="student" class="t_tok04.Student">
    <property name="name" value="스프링"></property>
</bean>
 
//Main.java
//스프링의 라이프 사이클
//스프링 컨테이너 생성
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
 
//스프링 컨테이너 설정
context.load("beans.xml");
context.refresh();//컨텍스트 초기화(안 하면 에러가 발생한다.)
//org.springframework.context.support.GenericXmlApplicationContext@1b2c6ec2 has not been refreshed yet
//스프링 컨테이너 사용
Student student = (Student)context.getBean("student");
System.out.println(student.getName());
 
//스프링 컨테이너 종료
context.close();
cs

 

[ Bean Life Cycle 관리방법 ]

1. 어노테이션을 통한 구현

어노테이션을 사용하기 위해서는 23행과 마찬가지로 반드시 context namespace를 추가해야 한다.

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
31
32
33
34
35
36
37
38
39
40
41
42
//Student.java
//어노테이션을 통해서 Bean Life Cycle을 관리하는 방법
//객체의 초기화 메서드. 메서드명은 아무거나 사용해도 된다.
@PostConstruct
public void postConstruct() {
    if("스프링".equals(name)) {
        System.out.println(name + "은 정말 열심히 하네요.");
    }else {
        System.out.println(name + "은 몇살인가요?");
    }
}
 
@PreDestroy
public void preDestroy() {
    if("스프링".equals(name)) {
        System.out.println("감사합니다. 열심히 하겠습니다.");
    }else {
        System.out.println("나이는 비밀입니다.");
    }
}
 
//beans.xml
<context:annotation-config/>
<bean id="student" class="t_tok04.Student">
    <property name="name" value="스프링"></property>
</bean>
 
//Main.java
//스프링의 라이프 사이클
//스프링 컨테이너 생성
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
 
//스프링 컨테이너 설정
context.load("beans.xml");
context.refresh();//컨텍스트 초기화(안 하면 에러가 발생한다.)
//org.springframework.context.support.GenericXmlApplicationContext@1b2c6ec2 has not been refreshed yet
//스프링 컨테이너 사용
Student student = (Student)context.getBean("student");
System.out.println(student.getName());
 
//스프링 컨테이너 종료
context.close();
cs

 

2. 인터페이스를 통한 구현

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
31
32
33
34
35
36
37
//Student.java
public class Student implements InitializingBean, DisposableBean{
    //인터페이스를 통해서 Bean Life Cycle을 관리하는 방법
    //DisposableBean 인터페이스의 구현 메소드
    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Bean이 소멸될 때 호출된다. 자원을 반납할 부분이 있다면 여기서 진행한다. EX> DBCP커넥션 등 close()메소드 실행 시.");
    }
    //InitializingBean 인터페이스의 구현 메소드
    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Bean이 생성될 때 호출된다. Bean이 생성되어 스프링의 bean으로 등록되고, DI 이후에 초기화할 부분이 존재한다면 여기서 진행한다.");
    }
}
 
//beans.xml
<bean id="student" class="t_tok04.Student">
    <property name="name" value="스프링"></property>
</bean>
 
//Main.java
//스프링의 라이프 사이클
//스프링 컨테이너 생성
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
 
//스프링 컨테이너 설정
context.load("beans.xml");
context.refresh();//컨텍스트 초기화(안 하면 에러가 발생한다.)
//org.springframework.context.support.GenericXmlApplicationContext@1b2c6ec2 has not been refreshed yet
//스프링 컨테이너 사용
Student student = (Student)context.getBean("student");
System.out.println(student.getName());
 
//스프링 컨테이너 종료
context.close();
cs

 

3. Bean을 정의할 때 메서드를 지정하는 방법

bean 객체를 생성할 때, 초기와 종료시 실행할 메서드를 지정하는 속성을 명시한다.

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
31
//Student.java
//bean을 정의할 때 메소드를 지정하여 Bean Life Cycle을 관리하는 방법
//초기화 메소드. 메서드명은 아무거나 사용해도 된다. 
public void init() {
    System.out.println(name + "은 학생인가요?");
}
//소멸 메소드
public void cleanUp() {
    System.out.println(name + "은 학생이 아니었습니다.");
}
 
//beans.xml
<bean id="student" class="t_tok04.Student" init-method="init" destroy-method="cleanUp">
    <property name="name" value="스프링"></property>
</bean>
 
//Main.java
//스프링의 라이프 사이클
//스프링 컨테이너 생성
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
 
//스프링 컨테이너 설정
context.load("beans.xml");
context.refresh();//컨텍스트 초기화(안 하면 에러가 발생한다.)
//org.springframework.context.support.GenericXmlApplicationContext@1b2c6ec2 has not been refreshed yet
//스프링 컨테이너 사용
Student student = (Student)context.getBean("student");
System.out.println(student.getName());
 
//스프링 컨테이너 종료
context.close();
cs

'BackEnd > Spring' 카테고리의 다른 글

SpringLegacyProject_SpringSecurity적용하기  (0) 2022.07.12
Spring기초_Day6_웹 개발 모델  (0) 2022.07.11
Spring_Transaction_국비_Day89  (0) 2022.07.08
Spring_AOP_국비_Day87  (0) 2022.07.06
Spring_국비_Day86  (0) 2022.07.05