지난 시간에 스프링(Spring)의
DI(Dependency Injection)와
IOC 컨테이너(Container)를 학습했습니다
아직 안보고 오셨다면
아래의 링크 ↓↓
2020/09/23 - [Java] - [Java] 스프링(Spring) DI(Dependency Injection)과 IOC 컨테이너(Container)
오늘은 스프링의 컨테이너와 빈(Bean) 객체의
생명 주기(Life Cycle)와 범위(Scope)를 보겠습니다
1. applicationCTX.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="calculator" class="com.example.demo.Calculator" />
<bean id="myCalculator" class="com.example.demo.MyCalculator" scope="singleton">
<property name="calculator">
<ref bean="calculator"/>
</property>
<property name="firstNum" value="10" />
<property name="secondNum" value="2"></property>
</bean>
</beans>
2. Calculator.java
package com.example.demo;
public class Calculator {
public void addition(int firstNum, int secondNum) {
System.out.println("addition()");
int result = firstNum + secondNum;
System.out.println(firstNum + " + " + secondNum + " = " + result);
}
public void subtraction(int firstNum, int secondNum) {
System.out.println("subtraction()");
int result = firstNum - secondNum;
System.out.println(firstNum + " - " + secondNum + " = " + result);
}
public void multiplication(int firstNum, int secondNum) {
System.out.println("multiplication()");
int result = firstNum * secondNum;
System.out.println(firstNum + " * " + secondNum + " = " + result);
}
public void division(int firstNum, int secondNum) {
System.out.println("division()");
if ( secondNum == 0 ) {
System.out.println("It cannot be divided by zero.");
}
int result = firstNum / secondNum;
System.out.println(firstNum + " / " + secondNum + " = " + result);
}
}
3. MyCalculator.java
package com.example.demo;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class MyCalculator implements InitializingBean, DisposableBean {
Calculator calculator;
private int firstNum;
private int secondNum;
public MyCalculator() {
}
public void add() {
calculator.addition(firstNum, secondNum);
}
public void sub() {
calculator.subtraction(firstNum, secondNum);
}
public void mul() {
calculator.multiplication(firstNum, secondNum);
}
public void div() {
calculator.division(firstNum, secondNum);
}
public void setCalculator(Calculator calculator) {
this.calculator = calculator;
}
public void setFirstNum(int firstNum) {
this.firstNum = firstNum;
}
public void setSecondNum(int secondNum) {
this.secondNum = secondNum;
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("destroy()");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("afterPropertiesSet()");
}
}
4. MainClass.java
package com.example.demo;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
String configLocation = "classpath:applicationCTX.xml";
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load(configLocation);
ctx.refresh();
MyCalculator myCalculator1 = ctx.getBean("myCalculator", MyCalculator.class);
myCalculator1.add();
myCalculator1.sub();
myCalculator1.mul();
myCalculator1.div();
MyCalculator myCalculator2 = ctx.getBean("myCalculator", MyCalculator.class);
myCalculator2.add();
myCalculator2.sub();
myCalculator2.mul();
myCalculator2.div();
if ( myCalculator1 == myCalculator2 ) {
System.out.println("myCalculator1 == myCalculator2");
} else {
System.out.println("myCalculator1 != myCalculator2");
}
ctx.close();
}
}
위의 코드에서 컨테이너의 생명주기를
살펴보면 아래와 같습니다
빈(Bean)의 경우는
컨테이너가 소멸할 때 자동 소멸하게 되는데요
만약 빈만 소멸하게 하려면
위의 코드에서는 destroy()를 호출하면되겠죠?
또 빈이 초기화 또는 소멸할 때
호출되는 afterPropertiesSet()과 destory()를
InitializingBean, DisposableBean 인터페이스를
구현함으로써 정의할 수 있습니다
이 방법 외에도
@PostConstruct, @PreDestroy
이노테이션을 사용할 수 있는데요
아래의 코드를 참고하세요~
1. applicationCTX.xml
<?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: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-3.2.xsd">
<context:annotation-config />
<bean id="calculator" class="com.example.demo.Calculator" />
<bean id="myCalculator" class="com.example.demo.MyCalculator" scope="singleton">
<property name="calculator">
<ref bean="calculator"/>
</property>
<property name="firstNum" value="10" />
<property name="secondNum" value="2"></property>
</bean>
</beans>
2. MyCalculator.java
package com.example.demo;
import javax.annotation.*;
public class MyCalculator {
Calculator calculator;
private int firstNum;
private int secondNum;
public MyCalculator() {
}
public void add() {
calculator.addition(firstNum, secondNum);
}
public void sub() {
calculator.subtraction(firstNum, secondNum);
}
public void mul() {
calculator.multiplication(firstNum, secondNum);
}
public void div() {
calculator.division(firstNum, secondNum);
}
public void setCalculator(Calculator calculator) {
this.calculator = calculator;
}
public void setFirstNum(int firstNum) {
this.firstNum = firstNum;
}
public void setSecondNum(int secondNum) {
this.secondNum = secondNum;
}
@PostConstruct
public void initMethod() {
System.out.println("initMethod()");
}
@PreDestroy
public void destoryMethod() {
System.out.println("destoryMethod()");
}
}
마지막으로 빈의 범위(Scope)는
xml 파일에 scope으로 설정이 가능한데요
위의 코드에서는 singleton으로 설정했습니다
singleton 패턴에 대해 잘 모르신다면
아래의 링크 ↓↓
2020/06/14 - [Java] - [Design Pattern] 싱글톤(Singleton) 패턴과 프로토타입(Prototype) 패턴
이상으로 오늘의 학습을 마치겠습니다
그럼 이만-_-
'Java' 카테고리의 다른 글
[Java] 스프링(Spring) MVC(Model-View-Controller) (0) | 2020.09.28 |
---|---|
[Java] 스프링(Spring) AOP(Aspect-Oriented Programming) (0) | 2020.09.24 |
[Java] 스프링(Spring) DI(Dependency Injection)과 IOC 컨테이너(Container) (0) | 2020.09.23 |
[Java] 스프링(Spring) 환경 세팅하기 (0) | 2020.09.23 |
[Java] 직렬화(Serialization)와 역직렬화(Deserialization) (0) | 2020.08.20 |