웹 & 프레임워크

Spring DI(Dependency Injection) 출력도우미

늘근이 2014. 6. 27. 14:15

     private OutputService outputter = new OutputServiceImplConsole();

 

이건 별로 좋지않다. 왜냐면 우항을 계속 바꿔야하기때문

 

일단 콘솔에 찍는거랑, 파일에 뿌리는거랑 둘다 넘긴다.

위쪽에 new OutputServiceImplConsole();을 계속한다면 계속 소스를 바꾸고 컴파일을 해야하기 때문에

밑에 저렇게 써놓고 그냥 얘네들 받을수 있는거 준비만 한다.

 

           private OutputService outputter;


바로이게 마법의 문장이다. 아무 new도 안했다. 나머지는 spring이 해줄것이다.

 

 

 

package com.gorakgarak.sample1.setter;

 

public class GreetingServiceImpl implements GreetingService {

 

             // DI, 넣어줄수있어야한다

             // 여기서는 생성자를 이용하는방법과 setter 이용하는 방법이있다

             //여기는 인터페이스만 가져온다. (spring이선택하게함)

             private OutputService outputter;

 

             public void setOutputter(OutputService outputter) {

                           this.outputter = outputter;

             }

 

             public void sayHello(String name) {

                           outputter.output("Hello" + name);

             }

            

}

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

package com.gorakgarak.sample1.setter;

 

import java.io.FileWriter;

import java.io.PrintWriter;

 

public class OutputServiceImplFile implements OutputService {

 

                  @Override

                  public void output(String message) {

                                   PrintWriter out =null;

                                   try {

                                                     out = new PrintWriter(new FileWriter("log.txt",true));

                                                     //true이면 append, false  overwrite

                                                     out.println(message);

                                   } catch (Exception e) {

                                                     e.printStackTrace();

                                   }finally{

                                                     if(out != null){

                                                                       out.close();

                                                     }

                                   }

 

                  }

 

}

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

 package com.gorakgarak.sample1.setter;

 

public class OutputServiceImplConsole implements OutputService {

 

                  @Override

                  public void output(String message) {

                                   System.out.println(message);

 

                  }

 

}

 

이제beans1.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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

 

<bean id="greeting" class="com.scgorakgaraksa.sample1.setter.GreetingServiceImpl">

                  <property name="outputter">

                                   <ref bean="outputter"/>

                  </property>

                  </bean>

<bean id="outputter" class="com.gorakgarak.sample1.setter.OutputServiceImplConsole"/>

 

 

</beans>

 

 

 OutputServiceImplConsole 대신 OutputServiceImplFile 을 한다면 파일에 저장한다 설정한대로

나머지 코드는 다음과같다

 

package com.gorakgarak.sample1.setter;

 

public class GreetingServiceImpl implements GreetingService {

 

                  // DI, 넣어줄수있어야한다

                  // 여기서는 생성자를 이용하는방법과 setter 이용하는 방법이있다

                  //여기는 인터페이스만 가져온다. (spring이선택하게함)

                  private OutputService outputter;

 

                  public void setOutputter(OutputService outputter) {

                                   System.out.println("set.... : " + outputter);

                                   this.outputter = outputter;

                  }

 

                  public void sayHello(String name) {

                                   outputter.output("Hello" + name);

                  }

                 

}

 

 

 

//////////////////////////////////////////////////////////////////////////////////////////////////////

 

package com.gorakgarak.sample1.setter;

 

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

package com.gorakgarak.sample1.setter;

 

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class GreetingTest {

                  public static void main(String[] args) {

                                  

                                  

                                   //팩토리 기능및 의존성 관리  등등등을 제공하는 놈임

                                   //단순공장이 아님

                                   //컨테이너는 클래스패쓰부터 찾음.. 아니면 filesystem.. 써서 경로에 맞게 찾덩가

                                   //클래스의 시작은 src라고 할수있다

                                   ClassPathXmlApplicationContext context

                                   = new ClassPathXmlApplicationContext("beans1.xml");

                                   GreetingService bean = (GreetingService)context.getBean("greeting");

 

                                   bean.sayHello("김수현");

                                   bean.sayHello("현빈");

                                   bean.sayHello("김우빈");

                                   bean.sayHello("윤시윤");

                                  

                                  

                  }

}

 

 

 

제대로 설정을 안하면 NPE가 뜬다

의존성을 잘 알려줘야만 한다.

beans graph를 보면 의존성을 볼수있다

 

 

전체적인 구조를 이미지로 표현하면 다음과 같다

'웹 & 프레임워크' 카테고리의 다른 글

Spring bean 사용법  (0) 2014.06.27
Spring 구조 그림  (0) 2014.06.27
Spring 설치  (0) 2014.06.27
Spring 은 무엇이냐  (0) 2014.06.27
Jquery domtree 새로운 내용 추가해보기 <div>로  (0) 2014.06.27