Application Context는 객체 컨테이너라고도 한다.
스프링에서 빈을 관리하는 컨테이너이다.
스프링에서는 객체를 직접 생성하는 대신 객체 컨테이너를 사용하여 객체(Bean)을 자동으로 관리하고 주입한다.
스프링에서 사용되는 빈을 생성하고, 필요한 곳에 자동으로 제공하는 역할을 한다.
XML 파일, Java Config, Annotation 등을 이용해 객체를 생성하고 설정할 수 있다.
서로 의존하는 객체를 new 없이 자동으로 연결해 준다.
ApplicationContext ac = new ClassPathXmlApplicationContext("config.xml");
Car car = (Car)ac.getBean("car");
Engine engine = (Engine)ac.getBean("engine");
ApplicationContext가 config.xml을 읽고 car와 engine객체를 자동으로 생성한다.
ac.getBean("car")을 호출하면 미리 생성된 Car객체를 가져온다.
class Car{}
class SportsCar extends Car{}
class Truck extends Car{}
class Engine{}
class AppContext{
Map map; //맵 생성
AppContext(){ //생성자
map = new HashMap(); //맵을 해시맵으로 생성
map.put("car",new SportsCar()); //맵에 객체를 넣음
map.put("engine",new Engine());
}
Object getBean(String key){ //key에 따른 객체를 리턴
return map.get(key);
}
}
public class Main2 {
public static void main(String[] args) throws Exception {
AppContext ac = new AppContext(); //AppContext 객체 생성
Car car = (Car)ac.getBean("car"); //생성한 객체 ac의 getBean함수 호출
System.out.println("car: "+car);
Engine engine = (Engine)ac.getBean("engine");
System.out.println("engine: "+engine);
}
}
위 코드는 만들 객체를 수정할 때마다 코드도 함께 수정해줘야 한다.
-> 유지보수에 좋지 않음
아래 코드처럼 작성해야 유지보수에도 용이하다.
class Car{}
class SportsCar extends Car{}
class Truck extends Car{}
class Engine{}
class AppContext{
Map map;
AppContext(){ //생성자
try {
Properties p = new Properties();
p.load(new FileReader("config.txt"));
//properties에 있는 내용을 맵에 저장
map=new HashMap(p);
//반복문으로 map에 있는 key의 이름을 얻어서 객체를 생성하고 다시 맵에 저장
for(Object key : map.keySet()){
Class clazz = Class.forName((String)map.get(key));
map.put(key,clazz.newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Object getBean(String key){
return map.get(key);
}
}
public class Main2 {
public static void main(String[] args) throws Exception {
AppContext ac = new AppContext();
Car car = (Car)ac.getBean("car");
System.out.println("car: "+car);
Engine engine = (Engine)ac.getBean("engine");
System.out.println("engine: "+engine);
}
}
Map은 <String, Object>
Properties는 <String, String>
1. Properties를 선언(p)한다.
2. config.txt파일을 읽어오고, 그 내용을 Map에 저장한다. (<String, String>)
3. for문을 돌며 현재 맵에 있는 모든 value를 객체로 변환한다.
getBean()은 이렇게 만든 map에서 key값에 맞는 객체를 찾아 반환하는 함수이다.