[필기정리] Day108 - Spring 실습문제

Web/Spring

2020. 11. 25. 14:31

# Property(멤버변수)를 활용한 DI

Q1. 아래의 코드들을 참고하여

- MyInfo.java

package com.tistory.coderbear;

import java.util.ArrayList;

public class MyInfo {
	private String name;
	private double height;
	private double weight;
	private ArrayList<String> hobbys;
	private BMICalculator bmiCalculator;
	
	
	public BMICalculator getBmiCalculator() {
		return bmiCalculator;
	}
	public void setBmiCalculator(BMICalculator bmiCalculator) {
		this.bmiCalculator = bmiCalculator;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public void setHobbys(ArrayList<String> hobbys) {
		this.hobbys = hobbys;
	}
	
	public void bmiCalculation() {
		bmiCalculator.bmicalculation(weight, height);
	}
	
	public void getInfo() {
		System.out.println("이름 : " + name);
		System.out.println("키 : " + height);
		System.out.println("몸무게 : " + weight);
		System.out.println("취미 : " + hobbys);
		bmiCalculation();
	}
}

- BMICalculator.java

package com.tistory.coderbear;

public class BMICalculator {
	private double lowWeight;
	private double normal;
	private double overWeight;
	private double obesity;
	
	public void bmicalculation(double weight, double height) {
		
		double h = height * 0.01 ;
		double result = weight / (h*h);
		
		System.out.println("BMI 지수 : " + (int)result);
		
		if(result > obesity) {
			System.out.println("비만 입니다.");
		} else if(result > overWeight) {
			System.out.println("과체중 입니다.");
		}else if(result > normal) {
			System.out.println("정상 입니다.");
		}else {
			System.out.println("저체중 입니다.");
		}
	}

	public void setLowWeight(double lowWeight) {
		this.lowWeight = lowWeight;
	}

	public void setNormal(double normal) {
		this.normal = normal;
	}

	public void setOverWeight(double overWeight) {
		this.overWeight = overWeight;
	}

	public void setObesity(double obesity) {
		this.obesity = obesity;
	}
}

-MainClass.java

package com.tistory.coderbear;

public class MainClass {

	public static void main(String[] args) {
	}

}


xml 파일에서 BMICalculator 객체 생성하면서 다음의 값으로 초기화를 하고

"lowWeight" 18.5 
"normal" 23 
"overWeight" 25 
"obesity" 30 


MyInfo 생성하면서 다음의 값으로 초기화 하자 

"name" 홍길동 
"height" 187 
"weight" 84 
"hobbys"  수영 요리 독서

"bmiCalculator"는 위에서 생성한 객체로 MainClass를 하나 만들고

MyInfo 객체를 getBean으로 얻어온 후 myInfo.getInfo() 메소드로 출력한다.

 

A.

- MyInfo.java

package com.tistory.coderbear;

import java.util.ArrayList;

public class MyInfo {
	private String name;
	private double height;
	private double weight;
	private ArrayList<String> hobbys;
	private BMICalculator bmiCalculator;
	
	
	public BMICalculator getBmiCalculator() {
		return bmiCalculator;
	}
	public void setBmiCalculator(BMICalculator bmiCalculator) {
		this.bmiCalculator = bmiCalculator;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public void setHobbys(ArrayList<String> hobbys) {
		this.hobbys = hobbys;
	}
	
	public void bmiCalculation() {
		bmiCalculator.bmicalculation(weight, height);
	}
	
	public void getInfo() {
		System.out.println("이름 : " + name);
		System.out.println("키 : " + height);
		System.out.println("몸무게 : " + weight);
		System.out.println("취미 : " + hobbys);
		bmiCalculation();
	}
}

- BMICalculator.java

package com.tistory.coderbear;

public class BMICalculator {
	private double lowWeight;
	private double normal;
	private double overWeight;
	private double obesity;
	
	public void bmicalculation(double weight, double height) {
		
		double h = height * 0.01 ;
		double result = weight / (h*h);
		
		System.out.println("BMI 지수 : " + (int)result);
		
		if(result > obesity) {
			System.out.println("비만 입니다.");
		} else if(result > overWeight) {
			System.out.println("과체중 입니다.");
		}else if(result > normal) {
			System.out.println("정상 입니다.");
		}else {
			System.out.println("저체중 입니다.");
		}
	}

	public void setLowWeight(double lowWeight) {
		this.lowWeight = lowWeight;
	}

	public void setNormal(double normal) {
		this.normal = normal;
	}

	public void setOverWeight(double overWeight) {
		this.overWeight = overWeight;
	}

	public void setObesity(double obesity) {
		this.obesity = obesity;
	}
}

- 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 configLocation = "applicationContext.xml";
		AbstractApplicationContext factory = new GenericXmlApplicationContext(configLocation);
		//스프링 컨테이너 생성
		MyInfo myInfo = (MyInfo)factory.getBean("myInfo");
		// 스프링 컨테이너에서 컴포넌트 가져옴
		myInfo.bmiCalculation();
		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="bMICalculator" class="com.tistory.coderbear.BMICalculator">
		<property name="lowWeight" value="18.5"/> // 멤버변수 일 때 property 태그 사용해야 함
		<property name="normal">
			<value>23</value>
		</property>
		<property name="overWeight" value="25"/>
		<property name="obesity" value="30"/>
	</bean>
	<bean id="myInfo" class="com.tistory.coderbear.MyInfo">
		<property name="name" value="홍길동"/>
		<property name="height" value="187"/>
		<property name="weight" value="84"/>
		<property name="hobbys">
			<list> // arrayList이기 때문
				<value>수영</value>
				<value>요리</value>
				<value>독서</value>
			</list>
		</property>
		<property name="bmiCalculator" ref="bMICalculator"/> // name = 멤버변수명 ref = 참조할 bean 이름
		<!--  
		<property name="bmiCalculator">
			<ref bean="bmiCalcaulator"/>
		</property>
		-->
	</bean>
</beans>

 

# 생성자를 활용한 DI

Q2. Student 클래스를 만든다.

     멤버변수로 다음과 같은 값을 둔다.

private String name;
private String age;
private String gradeNum;
private String classNum;

그리고 다음과 같은 생성자를 만든다.

public Student(String name, String age, String gradeNum, String classNum)

 

StudentInfo 클래스를 만들고 

멤버변수를 다음과 같이 두고

private Student student;

 

student를 초기화 해주는 생성자를 만든다.

student  setter 메소드를 만든다.

 

그리고 다음과 같이 학생 정보를 출력하는 메소드를 만든다.

public void getStudentInfo(){
     if(student != null) {
            System.out.println("이름 : " + student.getName());
            System.out.println("나이 : " + student.getAge());
            System.out.println("학년 : " + student.getGradeNum());
            System.out.println("반 : " + student.getClassNum());
            System.out.println("======================");                     
     }
}

 

그리고 xml에서 Student bean 2개를 만든다.

 

첫번째 빈은 생성자를 통해서 홍길동, 10, 3학년, 20번이라고 초기화를 해주고

두번째 빈도 생성자를 통해서 홍길순, 9, 2학년, 10번이라고 초기화 해준다.

 

StudentInfo bean 하나를 만들고 생성자에서 Student bean 만든 것 중에 첫번째 빈으로 초기화 해준다.

 

MainClass 를 하나 만들고 StudentInfo 빈을 불러와서 getStudentInfo메소드로 학생 정보를 출력한다.

그리고 xml에서 만든 두번째 학생 빈을 불러와서 방금전에 불러온 StudentInfo 빈에 학생 빈을 넣어준다.

그리고 getStudentInfo메소드로 학생 정보를 출력한다.

 

A.

- studentInfo.java

package com.tistory.coderbear;

public class StudentInfo {
	private Student student;

	public StudentInfo(Student student) {
		this.student = student;
	}
	
	public void setStudent(Student student) {
		this.student = student;
	}

	public void getStudentInfo(){
		if(student != null) {
			System.out.println("이름 : " + student.getName());
			System.out.println("나이 : " + student.getAge());
			System.out.println("학년 : " + student.getGradeNum());
			System.out.println("번호 : " + student.getClassNum());
			System.out.println("======================");
		}
	}
}

- Student.java

package com.tistory.coderbear;

public class Student {
	private String name;
	private String age;
	private String gradeNum;
	private String classNum;
	
	public Student(String name, String age, String gradeNum, String classNum) {
		this.name = name;
		this.age = age;
		this.gradeNum = gradeNum;
		this.classNum = classNum;
	}

	public String getName() {
		return name;
	}

	public String getAge() {
		return age;
	}

	public String getGradeNum() {
		return gradeNum;
	}

	public String getClassNum() {
		return classNum;
	}	
}

- 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);
		StudentInfo studentInfo = (StudentInfo)factory.getBean("studentInfo");
		studentInfo.getStudentInfo();
		
		Student student2 = (Student)factory.getBean("student2");
		studentInfo.setStudent(student2);
		studentInfo.getStudentInfo();
		
		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="student1" class="com.tistory.coderbear.Student">
		<constructor-arg name="name" value="홍길동"/> // 생성자 일 때 constructor-arg name="파라미터이름" 사용
		<constructor-arg name="age" value="10살"/>    // constructor-arg = constructor-argument  생성자-파라미터 의미
		<constructor-arg name="gradeNum" value="3학년"/>
		<constructor-arg name="classNum" value="20번"/>
	</bean>
	<!-- com.tistory.coderbear.Student student1 = new com.tistory.coderbear.Student("홍길동", "10살", "3학년", "20번") -->
	
    <bean id="student2" class="com.tistory.coderbear.Student">
		<constructor-arg name="name" value="홍길순"/>
		<constructor-arg name="age" value="9살"/>
		<constructor-arg name="gradeNum" value="2학년"/>
		<constructor-arg name="classNum" value="10번"/>
	</bean>
    <!-- com.tistory.coderbear.Student student2 = new com.tistory.coderbear.Student("홍길순", "9살", "2학년", 10번") -->
	
    <bean id="studentInfo" class="com.tistory.coderbear.StudentInfo">
		<constructor-arg name="student" ref="student1"/>
	</bean>
    <!--com.tistory.coderbear.StudentInfo studentInfo = new com.tistory.coderbear.StudentInfo(student1);-->

</beans>

 

# 인터페이스를 활용한 DI

Q3. 

Pencil 인터페이스를 만들고 void use()라는 메소드를 만든다.

Pencil4B, Pencil6B, Pencil6BWithEraser 클래스가 Pencil 인터페이스를 구현하도록 하자.

Pencil4B 클래스에 void use() 라는 메소드를 만들고 "4B 입니다."라고 출력하도록 한다.

Pencil6B 클래스에 void use() 라는 메소드를 만들고 "6B 입니다."라고 출력하도록 한다.

Pencil6BWithEraser 클래스에 void use() 라는 메소드를 만들고 "6BWithEraser 입니다."라고 출력하도록 한다.

 

MainClass 에서 Spring configration 파일을 이용하여

Pencil4B, Pencil6B, Pencil6BWithEraser를 각각 한번씩 생성해보고 use라는 메소드를 호출해본다.

자바파일은 수정하지 않은채 Spring Configuration 파일을 수정하여 완성해보자.

 

A.

- Pensil.java

package com.tistory.coderbear;

public interface Pencil {
	void use();
}

- Pencil4B.java

package com.tistory.coderbear;

public class Pencil4B implements Pencil {

	@Override
	public void use() {
		System.out.println("4B 입니다.");
	}
}

- Pencil6B.java

package com.tistory.coderbear;

public class Pencil6B implements Pencil {

	@Override
	public void use() {
		System.out.println("6B입니다.");
	}
}

- Pencil6BWithEraser.java

package com.tistory.coderbear;

public class Pencil6BWithEraser implements Pencil {

	@Override
	public void use() {
		System.out.println("6BWithEraser입니다.");
	}
}

- 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);
		Pencil pencil = (Pencil)factory.getBean("pencil"); // 다형성 - 인터페이스가 인터페이스가 형성한 것을 사용할 수 있다
		pencil.use();
		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="pencil" class="com.tistory.coderbear.Pencil4B"/>
</beans>

 

// 소스코드는 그대로이나 XML에서 수정하면 해당 내용이 변경된다! ex) 4B -> 6B

 

# applicationContext.xml이 2개 이상인 경우

Q4. Family class를 만들고 다음을 멤버변수로 둔다

private String papaName; 
private String mamiName; 
private String sisterName; 
private String brotherName; 


public Family(String papaName, String mamiName) 생성자를 만든다.
그리고 각각의 setter, getter를 만들어 준다.

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> hobbys)


그리고 각각의 setter, getter를 만들어 준다.

StudentInfo 클래스를 만들고
멤버변수를 다음과 같이 두고

private Student student;

 

그리고 student를 초기화하는 생성자와 setter, getter를 만들어 준다.

그리고 xml 파일을 두개 만든다.
첫번째 xml 파일에서 student1 이라는 이름으로 Student 빈을 하나 만들고
생성자를 통해 홍길동, 10, 취미(수영, 요리)를 초기화
height 187 weight 84 property를 통해서 초기화 한다.

StudentInfo 빈을 하나 만들고 
멤버변수로 Student 참조변수를 두고
위에서 만든 빈으로 생성자를 이용하여 초기화 한다.

두번째 xml 파일에서 student3 이라는 이름으로 Student 빈을 하나 만들고
생성자를 통해 홍길자, 8, 취미(줄넘기, 공기놀이)를 초기화
height 126 weight 21 property를 통해서 초기화 한다.

family라는 이름으로 Family 빈을 하나 만들고 papaName(홍아빠)과 mamiName(홍엄마)은 

c 접두어로 초기화하고 sisterName(홍누나)은 p 접두어로 초기화 한다. 
그리고 brotherName은 property로 홍오빠로 초기화 한다.

MainClass를 하나 만들고 
첫번째 xml에서 만든 student1 빈을 불러와서 이름과 취미를 출력해준다.

첫번째 xml에서 만든 studentInfo를 불러와서 

거기에 있는 student 객체를 student2라는 이름으로 불러와서 이름과 취미를 출력해준다.
student1객체와 student2객체가 같으면 "student1 == student2" 이라고 출력해 준다,

xml로부터 student3이라는 이름으로 student3객체를 불러온다. 

student3객체의 이름을 출력한다. 

그리고 student1객체와 student3객체가 같으면 "student1 == student3"이라고 출력해 주고 

다르면 "student1 != student3"이라고 출력해 준다.

xml에서 family 객체를 불러와서 

family객체의 papaName, mamiName, sisterName, brotherName를 출력한다.

 

A.

- family.java

package com.tistory.coderbear;

public class Family {
	private String papaName;
	private String mamiName;
	private String sisterName;
	private String brotherName;
	
	public Family(String papaName, String mamiName) {
		this.papaName = papaName;
		this.mamiName = mamiName;
	}

	public String getPapaName() {
		return papaName;
	}

	public void setPapaName(String papaName) {
		this.papaName = papaName;
	}

	public String getMamiName() {
		return mamiName;
	}

	public void setMamiName(String mamiName) {
		this.mamiName = mamiName;
	}

	public String getSisterName() {
		return sisterName;
	}

	public void setSisterName(String sisterName) {
		this.sisterName = sisterName;
	}

	public String getBrotherName() {
		return brotherName;
	}

	public void setBrotherName(String brotherName) {
		this.brotherName = brotherName;
	}
}

- 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;
	}
}

- StudentInfo.java

package com.tistory.coderbear;

public class StudentInfo {
	private Student student;

	public StudentInfo(Student student) {
		this.student = student;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}
}

- 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 resourceLocations1 = "applicationContext1.xml";
		String resourceLocations2 = "applicationContext2.xml";
		AbstractApplicationContext factory = new GenericXmlApplicationContext(resourceLocations1, resourceLocations2);
		
		Student student1 = (Student)factory.getBean("student1");
		System.out.println("이름 : " + student1.getName());
		System.out.println("취미 : " + student1.getHobby());
		
		StudentInfo studentInfo = (StudentInfo)factory.getBean("studentInfo");
		Student student2 = (Student)studentInfo.getStudent();
		System.out.println("이름 : " + student2.getName());
		System.out.println("취미 : " + student2.getHobby());	
		
		if(student1 == student2){
			System.out.println("student1 == student2");
		}
		
		Student student3 = (Student)factory.getBean("student3");
		System.out.println(student3.getName());
		
		if(student1 == student3){
			System.out.println("student1 == student3");
		} else{
			System.out.println("student1 != student3");
		}
		
		Family family = (Family)factory.getBean("family");
		System.out.println(family.getPapaName());
		System.out.println(family.getMamiName());
		System.out.println(family.getSisterName());
		System.out.println(family.getBrotherName());
		
		factory.close();
	}
}

- applicationContext1.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="student1" class="com.tistory.coderbear.Student">
		<constructor-arg value="홍길동" />
		<constructor-arg value="10"/>
		<constructor-arg>
			<list>
				<value>수영</value>
				<value>요리</value>
			</list>
		</constructor-arg>
		<property name="height" value="187"/>
		<property name="weight" value="84"/>		
	</bean>
	
	<bean id="studentInfo" class="com.tistory.coderbear.StudentInfo">
		<constructor-arg ref="student1"/>
	</bean>	
</beans>

- applicationContext2.xml (namespace - 해당 파일의 하단 메뉴 중 한 개)

<?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:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="student3" class="com.tistory.coderbear.Student">
		<constructor-arg value="홍길자" />
		<constructor-arg value="8" />
		<constructor-arg>
			<list>
				<value>줄넘기</value>
				<value>공기놀이</value>
			</list>
		</constructor-arg>
		<property name="height" value="126" />
		<property name="weight" value="21" />

	</bean>
	<bean id="family" class="com.tistory.coderbear.Family" c:papaName="홍아빠" c:mamiName="홍엄마" p:sisterName="홍누나">
		<property name="brotherName" value="홍오빠" />
	</bean>
</beans>
<!-- c 접두어와 p 접두어를 쓰기 위해서 Namespaces 탭에서 c와 p를 체크한다. -->

 

# annotation(어노테이션)을 통한 DI

Q5. 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과 student2를 만든다.

annotation을 통해서 student1을 다음과 같이해서 만든다.

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


annotation을 통해서 student2를 다음과 같이해서 만든다.

취미 독서, 음악감상 
이름 홍길순, 나이 18 키 170, 몸무게 55 


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 setHobbys(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 // context.xml과 동일 역할 수행 의미
public class ApplicationConfig {

	@Bean //  bean 태그와 동일한 것
	public Student student1(){ //Student 자료형 student1는 Bean id
		ArrayList<String> hobby = new ArrayList<String>();
		hobby.add("수영");
		hobby.add("요리");
		Student student = new Student("홍길동", 20, hobby);
		student.setHeight(180);
		student.setWeight(80);
		return student;
	}
	
	@Bean
	public Student student2(){ //Student 자료형 student2는 Bean id
		ArrayList<String> hobby = new ArrayList<String>();
		hobby.add("독서");
		hobby.add("음악감상");
		Student student = new Student("홍길순", 18, hobby);
		student.setHeight(170);
		student.setWeight(55);
		return student;
	}
}

- MainClass.java

package com.tistory.coderbear;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext factory = new AnnotationConfigApplicationContext(ApplicationConfig.class);
		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();
	}
}

- log4j.xml // 콘솔에 로그 남기는 라이브러리 "log4j"의 설정하는 역할

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p: %c - %m%n" />
		</layout>
	</appender>
	
	<!-- Application Loggers -->
	<logger name="com.tistory.coderbear">
		<level value="info" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.beans">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="info" />
	</logger>

	<logger name="org.springframework.web">
		<level value="info" />
	</logger>

	<!-- Root Logger -->
	<root>
		<priority value="warn" />
		<appender-ref ref="console" />
	</root>
	
</log4j:configuration>

- pom.xml // 메이븐(빌드 프레임워크) 설정 파일

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tistory</groupId>
	<artifactId>ex</artifactId>
	<name>Test4</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
	
		<dependency>   <!-- 추가 -->
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.2.0</version>
		</dependency>

	
		<dependency>	<!-- 추가 -->
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>3.2.0</version>
			<scope>test</scope>
		</dependency>		
		        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

// Tip : CGLib

 코드 생성 라이브러리로서(Code Generator Library)

 런타임에 동적으로 자바 클래스의 프록시를 생성해주는 기능을 제공한다.

 CGLIB를 사용하면 매우 쉽게 프록시 객체를 생성할 수 있으며, 성능 또한 우수하다.

           

 더불어, 인터페이스가 아닌 클래스에 대해서 동적 프록시를 생성할 수 있기 때문에

 다양한 프로젝트에서 널리 사용되고 있다.

       

 예를 들어, Hibernate는 자바빈 객체에 대한 프록시를 생성할 때 CGLIB를 사용하며,

               Spring은 프록시 기반의 AOP를 구현할 때 CGLIB를 사용하고 있다.

 

// pom.xml에 추가 필요

<dependency> <!-- 추가 --> 
<groupId>cglib</groupId> 
<artifactId>cglib</artifactId> 
<version>3.2.0</version> 
</dependency> 


<dependency> <!-- 추가 --> 
<groupId>cglib</groupId> 
<artifactId>cglib-nodep</artifactId> 
<version>3.2.0</version> 
<scope>test</scope> 
</dependency>

 

 

728x90