2016년 11월 2일 수요일

71day / Framework / spring Framework Annotation


http://www.skywayperspectives.org
spring Annotation활용
강사님은 언제나 동작원리를 강조하신다.
복붙을 하던 API를 퍼오던 그 속에 동작원리를 알고는 있어야 된다는 것이다!
때문에 어제 springMVC를 배울때는 xml방식으로 하고 오늘은 Annotation으로 배운듯 하다
실제로는 Annotation방식을 더 많이 사용한다고 한다.
(어쩐지 책이나 개인공부를 할때나 검색하면 Annotation으로된 예제가 많더라..)

Annotation?
주석이 선언적 프로그래밍 모델(설정정보 : 메타데이터)을 지원하는 기술 
 ex) @Repository , @Service , @Controller 
    @AutoWired , @Resource , @Inject , @Named 
 참고 ) 메타데이터 - 데이터의 데이터 
        데이터를 설명하기 위한 데이터 
        ex) 설정정보 
        
메타데이터로서의 xml과 Annotation 이점
xml : 유지보수성 측면
Annotation : 개발생산성 측면  
IT가 발전함에 따라 개발 및 유지보수의 규모가 커대해져 XML 설정 정보가 방대해진다 
-> Annotation은 직관적 메타데이터 설정이 가능 (소스와 메타데이터가 결합되는 형태)

시스템 전반에 영향을 주는 메타 데이터
XML로 설정하여 코드에 독립적으로 분리되어 정의되는 것이 바람직하다

설계시 확정되는 부분은 Annotation 기반
개발의 생산성을 향상시키는 것이 바람직하다 
    
Spring Annotation
Meta Data 로서의 역할

Spring Configuration(스프링 설정)
XML + Annotation   
     
Spring Annotation의 종류 
1. Component Annotation
@Repository : 영속성 계층에서 사용 
@Service : 비즈니스 계층에서 사용 
@Controller : 프리젠테이션 계층에서 사용 
   
2. Dependency Injection 
@AutoWired
의존 대상 객체를 타입으로 검색해 주입한다
만약 동일한 타입의 객체가 여러개 일 경우 -> Exception 발생 
@Resource
의존 대상 객체를 타입으로 검색해 주입  
    or
@Resource(name="bean id")
의존 대상 객체를 이름으로 검색해 주입      
@Inject
의존 대상 객체를 타입으로 검색해 주입  
@Named("bean id")
@Inject와 @Named를 함께 명시하면 이름으로 주입 
    
ex)  @Service
public class MemberServiceImpl{}
--> 위 클래스가 스프링 컨테이너에 의해 객체 생성시에는 
     별도의 이름 명시되어 있지 않으므로 
     소문자로 시작하는 memberServiceImpl bean이 생성된다 
           
spring 설정파일상에서의 Annotation 설정           
<!-- 어노테이션 설정: 의존관계설정(bean생성) -->
<context:component-scan base-package="org.kosta.springmvc13" />
<!-- 어노테이션 컨트롤러 설정 -->
<mvc:annotation-driven /> 

ex) web.xml
달라진 부분은 없다.
 <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>
cs

ex) disptacher-servlet.xml
Annotation을 명시하는 부분이 생겼다.
<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        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-4.2.xsd">
<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/views/" />
    <property name="suffix" value=".jsp"/>
</bean>
Controller 이하의 모든 클래스를 탐색해서 어노테이션 명시되어 있으면 객체 생성한다
<context:component-scan base-package="controller" />
어노테이션 컨트롤러 설정
<mvc:annotation-driven/>
</beans>
cs

ex) index.jsp
동일하게 .do로 요청한다
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Annotation test</title>
</head>
<body>
    <a href="hello.do">hello.do test</a>
</body>
</html> 
cs

ex) Controller.java
@를 주목하자
@Controller
public class AnnotationController {
    @RequestMapping("hello.do")
    public String hello(){
        return "result";
    }
}
cs




Annotation을 사용하니 참으로 간편해졌다...
xml에서 DI를 적용하는 부분에서 굉장히 애먹었던 것이 없어지니
참으로 홀가분한 기분이다
하지만 Annotation만 사용할 수는 없는 법 xml도 익숙해지자

0 개의 댓글:

댓글 쓰기