에버노트 정리 원본 (사진포함)

==> https://www.evernote.com/shard/s350/sh/5da25168-e641-4739-9265-85e304f83582/1d1f613e5e504641e35df5a3c48e8e0b


----------------------------------------------------------------------------------------------------------------


2017.04.11 화

JUnit : 단위테스트를 지원하는 프레임워크
1. JUnit Library 준비
2. POJO형태의 Java 클래스 작성
@Before
  - 테스트 메서드를 수행하기전에 꼭 해야하는것들(초기화)
 @Test
 - 반드시 접근public,  리턴타입 void
  Assert.assertSame(expected, actual);
     //assert는 static이기때문에,  import static org.junit.Assert.assertSame; 작성후 assertSame으로 사용가능
  //(arg1,arg2) expected : 기대되어지는 결과문자열 / actual : 실행값 /equals라고 생각하면됨->true 반환시 성공함
@After
 - 테스트 후처리 필수 수행문장(close등)   
@Ignore
 - 테스트를 수행하지 않는다 (@Test @Ignore로 사용)


 public class Example {
    File output;
    @Before public void createOutputFile() {
          output= new File(...);
    }
    @Test public void something() {
          ...
    }
    @After public void deleteOutputFile() {
          output.delete();
    }
 }

     
 2-1 프로젝트선택후 우클릭 > Build Path > Configure Build Path

  2-2 Add Library > JUnit  > Next
 2-3 JUnit4  > Finish
  추가된거 확인후 Apply




ex : JUnit으로 테스트하면 정상값이나온경우 초록색이 나타남




Spring Test( Core 는 JUnit)
   --> pom.xml 에 복사하여 down받는다.
2.Test class 선언부
  @Runwith(SpringJunit4ClassRunner.class)
  @ContextConfiguration("config/Beans.xml"); //xml 경로지정
  @Autowired
  private ApplicationContext // 굳이 getBean을 여러번 하지 않아도 된다.
  --> 의존관계가 있는 객체를 자동으로 주.입(Injection)해주는 어노태이션
  @Qualifier("bean id "); // 동일한 클래스의 bean이 여러개있는경우, bean id를 지정해주는 방식(범위를 한정시킴)
  @Component : bean을 등록할때 사용  (컴포넌트는 대표이고, 특화된것을 사용하고싶으면 repository,service,controller
  - @Repository : DAO 객체
  - @Service : 서비스 객체
  - @Controller : 웹화면쪽 연결 Controller 객체 /  web tear(톰캣상에서 실행)
  @Resource : 의존관계




DI 구현방식
 ㅇ XML 사용하는 방식(bean등록 dependency 설정)

<bean id ="helloC" class="xxx.Hello">
     <property name="name" value="jeogwon"></property>
     <property name="printer" ref="stringPrinter"></property>
</bean>

<bean id="stringPrinter" class="xxx.StringPrint">
</bean>

 ㅇ Annotation을 사용하는 방식 (spring 2.5버전이후 생성됨)
@Component
public class Hello{
     @Value("jeongwon")
     String name;
    
     @Autowired
     @Quilifier("stringPrinter")
     Printer printer;
}

@Component("stringPrinter")
public class StringPrinter implements Printer{
}
 어노태이션 : xml설정 덜하고, 소스에 직접박혀있어서 사용하기에는 편하지만, bean은 그래프로 되어있어서 한눈에 파악하기 쉬움
개발 타이밍 : 어노태이션 / 운영 : xml(빈 그래프)


bean.xml
<!-- properties 파일의 정보를 설정 -->
<context:property-placeholder location="classpath:config/values.properties"/>

WAS : EJB Container + Web Container (ex : 웹로직,제우스..)



ORM(Object Relational Mapping) Framework
 - MyBatis(iBatis)
 - Hibernate
 - JPA(Java Persistance API)


JDBC->Spring JDBC -> MyBatis

DBCP(DataBase Connection Pooling) 
 -> 여러개 connection을 만든후, 재사용하여 사용 / 웹환경 필수 (ex : Apach DBCP common API 2.2.1)
pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.1.1</version>
</dependency>



SDDS(SimpleDriverDataSource)
Beans.xml
<!-- DataSource 설정 -->
<bean id='dataSource' class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="${db.driverClass}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>





ojdbc
 다운로드후, pom.xml 에 저장된 경로 추가
<!-- JDBC 추가 -->
<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>6</version>
<scope>system</scope>
<systemPath>${basedir}/lib/ojdbc6.jar</systemPath>
</dependency>

Maven 생성확인



<참고>







'IT > SPRING' 카테고리의 다른 글

[파일] 스프링 정리  (0) 2017.04.29
[링크] Spring 관련 API  (0) 2017.04.29
[교육] Spring Framework 교육 (4일차)  (0) 2017.04.29
[교육] Spring Framework 교육 (3일차)  (0) 2017.04.29
[교육] Spring Framework 교육 (1일차)  (0) 2017.04.29
에버노트 정리 원본(사진포함)
==> http://www.evernote.com/l/AV6hL6sDfxNIubrImPXJS2417WVd_YTw81Y/

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2017.04.10 월

1일차 : DI
2일차 : MyBatis
3일차 : MyBatis + AOP
4일차 : Spring MVC


Spring 특징
  1. DI (Dependency Injection) 
  2. AOP (Aspect Oriented Programming)
    -  ex ) 공통모듈인 경우 코드가 변경되더라도, 가져다쓰는 의존관계쪽에 영향이 미치지 않도록 의존성을 낮춤
  3. MVC (Model View Controller)
  4. RESTful 
  5. Mybatis



개발환경 구성
DownLoad > C:\Spring FW (파일경로)
           C:\Spring FW\sts-bundle\sts-3.8.4.RELEASE>STS.exe (파일실행)
          
  1. JDK 1.8
  2. STS 4.6.3
  3. TOMCAT 8.0.43
  4. tomcat Server STS 등록
  5. Chrome Browser을 STS에 연결

(1) JDK 1.8 

(2) STS (Spring Tool Suit)https://spring.io/tools/sts/all (설치)
                                                        https://spring.io/tools/sts (설명)

(4) tomcat Server STS 등록

(5) Chrome Browser을 STS에 연결 : Window>Preferences> General>Web Browser

ㅇ 참고(전자정부 프레임워크)


사용하게 되는 Open Source 현황
  1. Spring  (framework) : DI, AOP, MVC, RESTful
  2. Mybatis (framework) : db와 연동시 사용(ex : JDBC)
  3. JUnit : 단위테스트 지원
  4. Maven : 배포, 라이브러리 관리(jar파일) 
     - Maven project를 생성( pom.xml)  - 인터넷 필수 (메이븐에 원격접속하여 download받음)
     - 인터넷 사용 불가한경우,  Maven 사이트에 들어가서 라이브러리(jar)만 다운로드후 Eclipse에 추가
     - 참고) Maven Repository : 
    https://mvnrepository.com/
               dependency를 복사해서 pom.xml에 넣으면 자동으로 jar 파일 다운로드 생성

     - 4.1 이클립스 메이븐 프로젝트 추가
      Window > Show View > Other > Maven Repositories

     - 4.2 메이븐 파일 위치 확인가능
              로컬 Repository--> C:\Users\owner\.m2\repository 

  5.  Log4j(Library)  : Level을 설정하여 Level별 로그를 볼수 있다 





<JAVA 프로젝트 생성 -> Maven Project로 변환>
1. JAVA Project 생성   : New > Java Project > Project Name : "Spring"
2. Conver to Maven Project
     
 - Maven 프로젝트로 변환후, 'M' 작은 아이콘과, pom.xml 파일이 생성된 부분을 확인할 수 있다.


3. Spring Tools > Add Spring Project Nature





  1. Maven 사이트에서 'Spring Context' 검색후, dependency를 다운로드
  1.  dependency 복사후, pom.xml 에 추가(jar 파일 추가 확인)








SPRING 의 정의
Spring은 Java Enterprise 개발을 편하게 해주는 Open Source 경량급(LightWeight) 애플리케이션 프레임워크다.

- EJB(Enterprise Java Beans) - zip하고 jar로 만들어서 ejb? 로 변환해서 WAS에서 배포
- POJO(Plian Old Java Object)





Spring 삼각형
이미지 출처 및 설명 : http://jinpyo900.tistory.com/55
(1) DI(Dependency Injection) : 의존관계 주입
  - IoC (Inversion of Control) 제어반전 구현
(2)AOP(Aspect Oriented Programming) : 관점지향
(3) PSA(Portable Service Abstractions) : 특정 밴더에 종속적이지 않고, 독립적인 형태로 api가 구성됨






실습 (사전실행)
1. http://blog.naver.com/vega2k      > SpringUserProject.zip 다운로드 

2.Project Import 
3. SpringWebPrjMY의 value.properties IP를 변경(강의실 IP)


4.실행(CRUD)






Framework와 Library의 차이점


Library의 특징
ㅇ 제어(Control)을 개발자가함

Framework 의 특징 ( Library 적 요소 + Container) 
ㅇ Library  적인 요소를 가지고 있음 
ㅇ 제어의 주도권을  가지고 있다.
ㅇ Container적 기능을 제공함(객체생성,소멸)
ㅇ ex ) tomcat , Mybatis, Spring
--> IoC (Inversion of Control) 제어반전 


Framework의 구성요소
1) IoC 컨테이너 (제어권을 가져가서 컨테이너 기능을 제공해야함)
 - 객체의 생성, 소멸, 객체 메서드 호출
2)Library인 요소
3)Design Pattern
  - GOF패턴, J2EE 패턴



IoC(Inversion of Control) 구현
ㅇ DL : Dependency Lookup
ㅇ DI : Dependency Injection


ㅇ Depend on Interface

ㅇ Do not Depend on Implementation

=> 인터페이스에는 의존하되, 구현체에는 의존하지 말아라

Setter Injection : setter 메서드의 인자(argument)에 의존하는 객체를 주입
Constructure Injection : 생성자 인자에 의존하는 객체를 주입




개발자의 역할
1. Spring Bean 설정 파일 작성(xml)
 - config > bean.xml 파일



 - bean 
<constructure-arg index="0" values="홍길동">

2. IoC 컨테이너 역할을 하는 클래스 사용

ApplicationContext context = new GenericXmlApplication (config/beans.xml) //직접생성 필요,  XML위치 지정

Hello hello = Context.getBean(“hello”); //캐스팅필요

hello.print();





<<실습2- Bean 생성및 그래프 보기 >>

1.  New > Spring Bean Configuration File


2.config > Beans.xml , bean체크후  Finish



3.  Beans.xml 내용 추가
<!-- Hello 클래스를 bean으로 등록 -->
<bean id = "hello" class="myspring.di.xml.Hello">
<property name ="name" value="jeongwon"></property>
<property name ="printer" ref="stringPrinter"></property>
</bean>

<!-- StringPrinter 클래스를 bean으로 등록 -->
<bean id = "stringPrinter" class="myspring.di.xml.StringPrinter">
</bean>

<!-- ConsolePrinter 클래스를 bean으로 등록 -->
<bean id = "consolePrinter" class="myspring.di.xml.ConsolePrinter">
</bean>
   Beans.xml 의 Graph를 한눈에 볼 수 있음








XML 문서의 구조를 정의해놓은 것  : XML 스키마(XSA)



코드
package myspring.di.xml.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import myspring.di.xml.Hello;

public class HelloBeanTest {

public static void main(String[] args) {
      //1.IoC 컨테이너 객체 생성(객체생성을 직접하지 않고, 객체생성을 해준애(Bean)한테 객체를 받아옴)
     ApplicationContext context= new GenericXmlApplicationContext("config/beans.xml");
     Hello hello = (Hello)context.getBean("hello");
     Hello hello2 = context.getBean("hello", Hello.class);
     System.out.println(hello.sayHello()); // Hello Jeongwon  --> 2번째방법을 더 많이 사용한다
    
     hello.print();
     
     Printer printer = context.getBean("stringPrinter",Printer.class);
     System.out.println(printer.getClass().getName()); //myspring.di.xml.StringPrinter
     System.out.println(printer.toString()); //Hello Jeongwon
  }     

}

    ApplicationContext context= new GenericXmlApplicationContext("config/beans.xml");
    Hello hello = (Hello)context.getBean("hello");
    System.out.println(hello.sayHello()); // Hello Jeongwon 


<Bean의 Scope(범위) 지정 >
ㅇ Request : (웹환경)A-B 동안에만 객체생성이 이루어지게
ㅇ Session : 세션
ㅇ Singleton : 한번만. Default 값
ㅇ Prototype : 매번 객체생성 






'IT > SPRING' 카테고리의 다른 글

[파일] 스프링 정리  (0) 2017.04.29
[링크] Spring 관련 API  (0) 2017.04.29
[교육] Spring Framework 교육 (4일차)  (0) 2017.04.29
[교육] Spring Framework 교육 (3일차)  (0) 2017.04.29
[교육] Spring Framework 교육 (2일차)  (0) 2017.04.29

+ Recent posts