[필기정리] Day109-1 - annotation과 xml, Spring의 생명주기와 범위 등

Web/Spring

2020. 11. 26. 14:45

 

 

# xml으로 annotation(어노테이션) 호출하는 방식의 DI

Q1. Student 클래스에 멤버변수를 다음과 같이해서 만든다.

private String name; 
private int age; 
private ArrayList<String> hobby; 
private double height; 
private double weight;


다음과 같이 생성자를 만든다.

public Student(String name, int age, ArrayList<String> hobby) 


그리고 각각의 getter 메소드와 setter 메소드를 만든다.
Spring Bean Configuration File 없이 자바파일을 하나 만들고 student1을 만든다.
annotation을 통해서 student1을 다음과 같이해서 만든다.

취미 수영, 요리 
이름 홍길동, 나이 20 키 180, 몸무게 80 


xml파일을 통해서 annotation을 통해서 만든 객체를 로드시킨다.
그리고 xml 파일에서 student2 bean을 다음 값으로 만들자.
생성자를 통해서 이름 홍길순, 나이 30, 취미 마라톤, 요리, property를 통해서 키 190, 몸무게 70으로 만든다.

MainClass에서 xml파일을 읽어들인다. 

그리고  student1과 student2의 각각의 이름, 나이, 취미, 신장, 몸무게를 출력한다.

 

A.

- Student.java

package com.tistory.coderbear;

import java.util.ArrayList;

public class Student {
	private String name;
	private int age;
	private ArrayList<String> hobby;
	private double height;
	private double weight;
	public Student(String name, int age, ArrayList<String> hobby) {
		this.name = name;
		this.age = age;
		this.hobby = hobby;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public ArrayList<String> getHobby() {
		return hobby;
	}
	public void setHobby(ArrayList<String> hobby) {
		this.hobby = hobby;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
}

- ApplicationConfig.java

package com.tistory.coderbear;

import java.util.ArrayList;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {

	@Bean
	public Student student1(){
		ArrayList<String> hobby = new ArrayList<String>();
		hobby.add("수영");
		hobby.add("요리");		
		Student student = new Student("홍길동", 20, hobby);
		student.setHeight(180);
		student.setWeight(80);
		return student;
	}
}

- MainClass.java

package com.tistory.coderbear;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		String resourceLocations = "applicationContext.xml";
		AbstractApplicationContext factory = new GenericXmlApplicationContext(resourceLocations);
        // xml을 통한 컨테이너 생성
		Student student1 = (Student)factory.getBean("student1");
        // 생성자 가져옴
		System.out.println(student1.getName());
		System.out.println(student1.getAge());
		System.out.println(student1.getHobby());
		System.out.println(student1.getHeight());
		System.out.println(student1.getWeight());
		
		Student student2 = (Student)factory.getBean("student2");
		System.out.println(student2.getName());
		System.out.println(student2.getAge());
		System.out.println(student2.getHobby());
		System.out.println(student2.getHeight());
		System.out.println(student2.getWeight());
		
		factory.close();
	}
}

- applicationContext.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 class="com.tistory.coderbear.ApplicationConfig"/>
	
	<bean id="student2" class="com.tistory.coderbear.Student">
		<constructor-arg value="홍길순"/>
		<constructor-arg value="30"/>
		<constructor-arg>
			<list>
				<value>마라톤</value>
				<value>요리</value>
			</list>
		</constructor-arg>
		<property name="height" value="190"/>
		<property name="weight" value="70"/>
	</bean>
</beans>

 

# annotation(어노테이션)이 xml을 품는 방식의 DI

Q2. Student 클래스에 멤버변수를 다음과 같이해서 만든다.

private String name; 
private int age; 
private ArrayList<String> hobby; 
private double height; 
private double weight; 


다음과 같이 생성자를 만든다.

public Student(String name, int age, ArrayList<String> hobby) 


그리고 각각의 getter 메소드와 setter 메소드를 만든다.
annotation을 통해서 student1을 다음과 같이해서 만든다.

취미 수영, 요리 
이름 홍길동, 나이 20 키 180, 몸무게 80 


그리고 xml 파일에서 student2 bean을 다음 값으로 만들자.
생성자를 통해서 이름 홍길순, 나이 30, 취미 마라톤, 요리, property를 통해서 키 190, 몸무게 70으로 만든다.
annotation 설정파일에서 xml파일에 있는 값을 가져온다.


MainClass에서 annotation설정파일을 읽어들인다. 

그리고 student1과 student2의 각각의 이름, 나이, 취미, 신장, 몸무게를 출력한다.

 

A.

- Student.java

package com.tistory.coderbear;

import java.util.ArrayList;

public class Student {
	private String name;
	private int age;
	private ArrayList<String> hobby;
	private double height;
	private double weight;
	public Student(String name, int age, ArrayList<String> hobby) {
		this.name = name;
		this.age = age;
		this.hobby = hobby;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public ArrayList<String> getHobby() {
		return hobby;
	}
	public void setHobby(ArrayList<String> hobby) {
		this.hobby = hobby;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
}

- ApplicationConfig.java

package com.tistory.coderbear;

import java.util.ArrayList;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("applicationContext.xml")  // 해당 xml 파일을 import 해주는 것
public class ApplicationConfig {

	@Bean
	public Student student1(){
		ArrayList<String> hobby = new ArrayList<String>();
		hobby.add("수영");
		hobby.add("요리");
		Student student = new Student("홍길동", 20, hobby);
		student.setHeight(180);
		student.setWeight(80);
		return student;
	}
}

- MainClass.java

package com.tistory.coderbear;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext factory = new AnnotationConfigApplicationContext(ApplicationConfig.class);
		
		Student student1 = (Student)factory.getBean("student1"); // student1 생성자 호출
		System.out.println(student1.getName());
		System.out.println(student1.getAge());
		System.out.println(student1.getHobby());
		System.out.println(student1.getHeight());
		System.out.println(student1.getWeight());
		
		Student student2 = (Student)factory.getBean("student2");
		System.out.println(student2.getName());
		System.out.println(student2.getAge());
		System.out.println(student2.getHobby());
		System.out.println(student2.getHeight());
		System.out.println(student2.getWeight());
		
		factory.close();
	}
}

- applicationContext.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">

	<bean id="student2" class="com.tistory.coderbear.Student">
		<constructor-arg value="홍길순"/>
		<constructor-arg value="30"/>
		<constructor-arg>
			<list>
				<value>마라톤</value>
				<value>요리</value>
			</list>
		</constructor-arg>
		<property name="height" value="190"/>
		<property name="weight" value="70"/>
	</bean>
</beans>

# Bean : Spring에서 POJO(Plain Old Java Object)

            애플리케이션의 핵심을 이루는 객체

            IOC(Inversion Of Control) 컨테이너에 의해 인스턴스화, 관리, 생성됨

 

[Spring] Spring Bean의 개념과 Bean Scope 종류 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

 

# 스프링의 생명주기(LifeCycle)

 

Q3. 스프링 컨테이너 생명주기를 생각하며 다음을 만들어 보자.
Student class를 만든다.
멤버변수로 이름과 나이가 있다.
그리고 두 멤버변수를 초기화 해주는 생성자가 있다.
각각의 getter, setter 메소드가 있다.
xml 파일에서 student라는 이름으로 객체를 만들고 생성자를 통해 이름 홍길순, 나이 30으로 초기화 해준다.
MainClass에서 xml을 로드시킨다. 그리고 student 객체를 가져와서 이름과 나이를 출력한다.

 

A.

- Student.java

package com.tistory.coderbear;

public class Student {
	private String name;
	private int age;
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

- MainClass.java

package com.tistory.coderbear;

import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		String resourceLocations = "applicationContext.xml";
		GenericXmlApplicationContext factory = new GenericXmlApplicationContext();	// 생성
		factory.load(resourceLocations);	// 설정
		factory.refresh();
		
		Student student = (Student)factory.getBean("student");		// 사용
		System.out.println("이름 : " + student.getName());
		System.out.println("이름 : " + student.getAge());
		
		factory.close();	// 종료
	}
}

- applicationContext.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="student" class="com.tistory.coderbear.Student">
		<constructor-arg>
			<value>홍길순</value>
		</constructor-arg>
		<constructor-arg>
			<value>30</value>
		</constructor-arg>
		<!--  
			<constructor-arg value="홍길순"></constructor-arg>
			<constructor-arg value="30"></constructor-arg>
		-->
	</bean>
</beans>

 

Q4. Student class를 만든다.
멤버변수로 이름과 나이가 있다.
그리고 두 멤버변수를 초기화 해주는 생성자가 있다.
각각의 getter, setter 메소드가 있다.
객체를 초기화하는 과정에서 호출되는 메소드와 소멸하는 과정에서 소멸되는 메소드를 

인터페이스를 이용하여 구현하시오.

xml 파일에서 bean을 Student클래스의 student라는 이름으로 하고 

생성자를 통해 이름 홍길순, 나이 30으로 한다.

MainClass에서 xml을 로드시킨다.
그리고 student의 이름과 나이를 출력해보자.

 

A.

- Student.java

package com.tistory.coderbear;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Student implements InitializingBean, DisposableBean{
	private String name;
	private int age;
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("afterPropertiesSet()");
	}
//	afterPropertiesSet() 은 InintializingBean 인터페이스의 메소드로 빈 초기화 과정에서 호출된다.
	@Override
	public void destroy() throws Exception {
		System.out.println("destroy()");
	}
//	DisposableBean은 스프링 빈(Bean)이 소멸될 때 호출된다. (destroy 메서드)
}

- MainClass.java

package com.tistory.coderbear;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		String resourceLocations = "applicationContext.xml";
		AbstractApplicationContext factory = new GenericXmlApplicationContext(resourceLocations);
		Student student = (Student)factory.getBean("student");
		System.out.println("이름 : " + student.getName());
		System.out.println("나이 : " + student.getAge());
		
		factory.close();
	}
}

- applicationContext.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="student" class="com.tistory.coderbear.Student">
		<constructor-arg value="홍길순"/>
		<constructor-arg value="30"/>
	</bean>
</beans>

 

# 스프링의 범위(Scope)

ex)

<bean id="student" class="com.tistory.coderbear.Student" scope="singleton">
		<constructor-arg value="홍길순"/>
		<constructor-arg value="30"/>
	</bean>

// scope는 별도로 지정하지 않으면 singleton을 디폴트 값으로 가진다.

 

- Scope 옵션 종류

옵션종류 설명
singleton 하나의 Bean 정의에 대해 Spring IOC Container 내에 단 하나의 객체만 존재하는 것, 디폴트 값
컨테이너가 사라질 때 bean도 제거됨
prototype 하나의 Bean 정의에 대해 다수의 객체 존재 가능
request 하나의 Bean 정의에 대해 하나의 HTTP request의 생명주기 안에 단 하나의 객체만 존재
즉, 각각의 HTTP request는 자신만의 객체를 가짐
Web-aware Spring ApplicationContext 안에서만 유효
session 하나의 Bean 정의에 대해 하나의 HTTP request의 생명주기 안에 단 하나의 객체만 존재
Web-aware Spring ApplicationContext 안에서만 유효
global session 하나의 Bean 정의에 대해 하나의 global HTTP request의 생명주기 안에 단 하나의 객체만 존재
일반적으로 portlet context 안에서 유효
Web-aware Spring ApplicationContext 안에서만 유효

 

Q5. Student class를 만든다.
멤버변수로 이름과 나이가 있다.
그리고 두 멤버변수를 초기화 해주는 생성자가 있다.
각각의 getter, setter 메소드가 있다.


xml 파일에서 bean을 Student클래스의 student라는 이름으로 하고 

생성자를 통해 이름 홍길순, 나이 30으로 한다.
MainClass에서 student 객체를  student1이라는 이름으로 불러와 이름과 나이를 출력한다. 

그런 후에 student 객체를 student2라는 이름으로 불러와

이름 홍길자, 나이 100으로 바꾼후에 이름과 나이를 출력한다.

그리고 student1과 student2가 서로 같은 객체이면 "student1 == student2"라고 출력하고

아니면 "student1 != student2"라고 출력하자.

 

A.

- Student.java

package com.tistory.coderbear;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Student implements InitializingBean, DisposableBean{
	private String name;
	private int age;
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("afterPropertiesSet()");
	}
	@Override
	public void destroy() throws Exception {
		System.out.println("destroy()");
	}
}

- MainClass.java

package com.tistory.coderbear;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		String resourceLocations = "applicationContext.xml";
		AbstractApplicationContext factory = new GenericXmlApplicationContext(resourceLocations);
		
		Student student1 = (Student)factory.getBean("student");
		System.out.println("이름 : " + student1.getName());
		System.out.println("나이 : " + student1.getAge());
		
		System.out.println("==============================");
		
		Student student2 = (Student)factory.getBean("student");
		student2.setName("홍길자");
		student2.setAge(100);
		
		System.out.println("이름 : " + student2.getName());
		System.out.println("나이 : " + student2.getAge());
		
		System.out.println("==============================");
		
		if(student1==student2){
			System.out.println("student1==student2");
		} else if(student1!=student2){
			System.out.println("student1!=student2");
		}
		
		factory.close();
	}
}

- applicationContext.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="student" class="com.tistory.coderbear.Student" scope="singleton">
		<constructor-arg value="홍길순"/>
		<constructor-arg value="30"/>
	</bean>
</beans>
// scope 생략 시 싱글톤 패턴이 디폴트, 싱글톤 패턴 시 객체를 한 개로 제한한다.

 

 

728x90