2013. 7. 29. 17:23

출처 : http://www.zetswing.com/bbs/board.php?bo_table=MySQL_LEC&wr_id=50


select * from goods where name like replace(name,' ','') like '%$name%';
(goods table에서 name필드의 공백을 제거하고 변수와 like 비교검색)
 
select count(*) from goods where left(signdate,10) = curdate()
(goods table에서 signdate(data타입)의 좌측의 10개문자만 가져와서 오늘 날짜와 비교)
 
select * from goods where from_unixtime(orderdate) between '2003-01-01' and '2004-01-01';
(goods table에서 timestamp형인 날짜형을 실제 날짜와 비교시  from_unixtime()함수로변환해사용)
 
select SUM(if(paymethod='bank',round(payM/exchange),payM)) from trade;
(trade테이블에서 paymethod컬럼의 값이 bank이면 round(payM/exchange) 의값들을 아니면 payM의 값들의 합을 출력합니다.)
 
select g.name,count(tg.idx) from goods as g,trade_goods as tg where g.idx=tg.goodsIdx  group by g.idx order by 2 desc;
(goods와 trade_goods을 조인하여 trade_goods 테이블에서 판매된 상품의 idx별로 그룹지어 2번째 출력컬럼인 count(tg.idx)의 오름차순으로 출력합니다.)
 
select code,count(code) from goods group by code having count(code)>1
(goods table에서 code 별로 그룹지어 count(code)의 갯수가 2개 이상인것만 출력합니다.)
 
select name,count(tradecode) from trade_goods where tradecode='$tradecode' group by tradecode having count(tradecode)>1;
(tradecode table에서 $tradecode변수와 tradecode컬럼이 같은 레코드에서 tradecode별로 정렬하고 그룹별갯수가 1개 이상인것만 출력한다.)-(주문서 중복 확인 쿼리)


'DBMS > MySQL' 카테고리의 다른 글

Mysql에서의 null값 고찰  (0) 2013.07.29
MYSQL 성능 향상 정리  (0) 2013.07.29
JOIN(조인) 사용하기  (0) 2013.07.29
4.0 추가기능  (0) 2013.07.29
[MySQL] 자동증가값  (0) 2013.07.29
Posted by 1+1은?
2013. 7. 29. 17:18

INNER JOIN (교집합)

 

INNER JOIN(NORMAL JOIN)은 여러 테이블의 조건들이 모두 만족했을때만 데이타를 보여주게 되며 한쪽 테이블의 조건이라도 만족하지 않으면 데이타를
보여주지 않습니다.

 

LEFT OUTER JOIN (교집합)

 

LEFT OUTER JOIN(교집합)은 여러 테이블의 조건들이 모두 만족하지 않더라도 데이타를 보여줍니다.

 

※ 조건이 만족하지 않는 테이블의 데이타값은 "NULL" 값으로 출력된다.

 

간단한 조인 예제

 

개요

 

출석 테이블을 만든다 가정하면 normal join 으로는, 한번도 출석하지 않은 학생은 목록에도 보이지 않게 되지만, outer join 으로는 모두 볼 수 있게 됩니다.

 

예제

 

[테이블 생성]

 

drop table book;
create table book
(
code varchar(10),
name varchar(10)
);
insert into book values ('1111','사랑책');
insert into book values ('2222','이별책');
insert into book values ('3333','웃긴책');

 

drop table animal;

create table animal
(
code varchar(10),
name varchar(10)
);
insert into animal values ('1111','사자');
insert into animal values ('2222','호랑이');
insert into animal values ('3333','오리');

 

drop table buy;
create table buy
(
book_code varchar(10),
animal_code varchar(10)
);
insert into buy values ('1111','1111');
insert into buy values ('2222','2222');
insert into buy values ('3333','4444');

 

[LEFT OUTER JOIN 예제]

 

select
 b.name, c.name
from
 buy as a
 left outer join book as b on a.book_code = b.code
 left outer join animal as c on a.animal_code = c.code;

 

※ left outer join 시에는 최대한 중복건이 안나오도록 유일한 컬럼으로 비교해야 한다.

※ left outer join 시에 조건에 만족하지 않는 테이블의 컬럼값은 "NULL" 로 표기된다.

 

[INNER JOIN 방법1]

 

select 
 b.name, c.name
from
 buy as a
 inner join book as b on a.book_code = b.code
 inner join animal as c on a.animal_code = c.code;

 

[INNER JOIN 방법2]

 

select 
 b.name, c.name
from
 buy as a, book as b, animal as c
where
 a.book_code = b.code and a.animal_code = c.code where a.code = '1111';

select 
 b.name, c.name
from
 buy as a, book as b, animal as c where a.book_code = '1111';

 

여러 테이블 컬럼의 모든 경우의 수를 출력한다.

 

select * from book, animal, buy;

select * from book a, animal b, buy c;

 

-- 3개테이블 컬럼의 경우의 수를 모두 출력한다.

-- 모든 경우의 수 = 각테이블의 로우스를 곱한값

 

RDBMS에서 JOIN은 중요한개념입니다.

서로 관련된 정보 중 정보의 관계가 1:N으로 설계하게 되면 서로 분리하여 2개의 테이블로 분리시킵니다. 여러개로 나누면서 서로 연결할수있는 공통 컬럼을 만들어두면 여러모로 좋은점이

많습니다. 그렇다고 table하나로 해결하는것이 효율적이지 않다는것은 아니지만 각각의 장단점이

있습니다.

 

table category

create table category(

num int not null primary key auto_increment,

name varchar(20) not null)

insert into category values(null,'컴퓨터');

insert into category values(null,'가전제품');

insert into category values(null,'통신기기');

 

table s_category

create table s_category(

num int not null primary key auto_increment,

cate_num int not null,

name varchar(20) not null)

insert into s_category values(null,1,'cpu');

insert into s_category values(null,2,'냉장고');

insert into s_category values(null,3,'pcs');

 

category 와 s_category테이블을 통해 어떤 대분류에 속한 소분류가 있는지 알아보자

ex)select * from category ,s_category where category.num=s_category.cate_num;

만약에 where절을 주지 않게 되면 table category와 table s_category를 곱한 값이

나오게 됩니다.

category의 첫번째 레코드를 가져온후 s_category의 첫번째레코드를 가져와 조건이 맞으면 출력

category의 첫번째 레코드를 가져온후 s_category의 두번째레코드를 가져와 조건이 맞으면 출력

category의 첫번째 레코드를 가져온후 s_category의 세번째레코드를 가져와 조건이 맞으면 출력

 

category의 두번째 레코드를 가져온후 s_category의 첫번째레코드를 가져와 조건이 맞으면 출력

category의 두번째 레코드를 가져온후 s_category의 두번째레코드를 가져와 조건이 맞으면 출력

category의 두번째 레코드를 가져온후 s_category의 세번째레코드를 가져와 조건이 맞으면 출력

..........

 

where 조건이 없으므로 위의 순서대로 모두 출력이 되는것이다.

 

또한 컴퓨터 카테고리에 속한 소분류만을 보고싶다면 다음과 같이 조인하면 된다.

ex)select a.num,a.name,b.num,b.name from category a,s_category b

where a.num=b.cate_num and a.num=1;


'DBMS > MySQL' 카테고리의 다른 글

MYSQL 성능 향상 정리  (0) 2013.07.29
초급QUERY  (0) 2013.07.29
4.0 추가기능  (0) 2013.07.29
[MySQL] 자동증가값  (0) 2013.07.29
Mysql insert 와 select 같이 쓰기  (0) 2013.07.29
Posted by 1+1은?
2013. 7. 29. 17:12

출처 : http://www.zetswing.com/bbs/board.php?bo_table=MySQL_LEC&wr_id=61


ssl연결,sql캐시,다중삭제,union,fulltext,외래키(Foreign Keys)


목차


union

ssl연결

SQL Cache 기능

fulltext

외래키(Foreign Keys)




union

 

-select 한 여러 결과를 한번에 서버로부터 가져오는 기능이다.


ex)

create table lee{
a int not null auto_increment primary key,
b char(10) null,
c blob null);
create table lee1{
a int not null auto_increment primary key,
b char(10) null,
c blob null);
적당히 lee와 lee1에 레코드를 입력하고

select * from lee union select * from lee1

select a,b from lee union select a,bzz from lee1

ad)컬럼의 수가 같고 각컬럼당 데이타형이 같아야합니다.


ssl연결

 

ssh클라이언트인 putty나 zterm으로 연결하듯이 mysql관리 클라이언트를 이용해 연결시

ssl을 이용해서 보안을 강화해서 연결한는것

 

SQL Cache 기능

 

처음 실행한 SQL의 결과를 캐시에 저장한후 이후에 같은 SQL을 실행시에 새롭게 실행하지 말고 캐시에 저장된 결과값을 가져오는 기술

※ 캐시 메모리를 이용하므로 속도가 빠르다.

※ 해당 머신의 캐시 메모리 크기가 크면 클수록 좋은 성능을 낸다.

※ ORACLE, MSSQL, DB2 와 같은 DBMS는 예전부터 지원하던 기능이다.

 

fulltext

 

통상적으로 어떤한 dbms라도 일반적인 방법으로는 like '%keyword%'와같은 조건으로 검색할때는 인덱스를 사용할수 없습니다. 

왜냐하면 keyword라는 단어가 문자열에서 어디에 있는지를 인덱스을 사용해도 알수없기 때문입니다. like keyword%와 같이 keyword로 시작하는 문자열을 찾을때는 인덱스를 사용할수있지만 keyword가 중간에 포함되는 문자열을 찾는 것은 단순한 인덱스로 해결할수 없습니다. 따라서 like '%keyword%'와 같은 쿼리는 어쩔수없이 모든 레코드를 검색해야하고 따라서 검색시간이 많이 걸립니다. 하지만 아쉅게도 게시판등의 시스템에서는 like '%keyword%' 와 같은 검색을 아주 많이 사용합니다. fulltext는 백터스페이스 모델을 이용하여 like '%keyword%'와 같은 쿼리도 인덱스를 사용할수있도록 해주는겁니다.

mysql4.0까지는 지원하지만 single byte만(1바이트-영문)만 지원합니다. 한글등 기타언어들은 2바이트인경우가 많아서 multibyte는 아직 지원하지 않습니다.

3.x대 지원안함

4.0대 지원함(싱글바이트)

4.1대 알파 지원함(싱글,멀티바이트는 불안함)

fulltext는 varchar나 text컬럼에 인덱스를 만들고 검색을 빠르게 할대 사용되지만 한국등의 멀티바이트는 지원하지 않습니다. fulltext는 막강한 기능이지만 아직 한글을 지원하지 않는다.

 

외래키(Foreign Keys)

현재도 3.x, 4.x 버전에서 INNO DB를 사용하면 지원 받을 수 있다. 하지만 기본 테이블인 MyISAM에서는 4.1 버젼부터 지원 예정이다.

'DBMS > MySQL' 카테고리의 다른 글

MYSQL 성능 향상 정리  (0) 2013.07.29
초급QUERY  (0) 2013.07.29
JOIN(조인) 사용하기  (0) 2013.07.29
[MySQL] 자동증가값  (0) 2013.07.29
Mysql insert 와 select 같이 쓰기  (0) 2013.07.29
Posted by 1+1은?
2013. 7. 29. 16:35

■ MVC 관련 Spring annotation - 2 


목차

@Service

@Repository

@Controller

@RequestMapping

@requestParam

@ModelAttribute

@SessionAttributes

@InitBinder



@Service


개요 : @Service를 적용한 Class는 비지니스 로직이 들어가는 Service로 등록이 된다.

 

Controller에 있는 @Autowired는 @Service("xxxService")에 등록된 xxxService와 변수명이 같아야 하며

Service에 있는 @Autowired는 @Repository("xxxDao")에 등록된 xxDao와 변수명이 같아야 한다.


@Service("helloService")
      public class HelloServiceImpl implements HelloService {
    @Autowired
    private HelloDao helloDao;
           public void hello() {
  System.out.println("HelloServiceImpl :: hello()");
  helloDao.selectHello();
     }
      }

helloDao.selectHello(); 와 같이 @Autowired를 이용한 객체를 이용하여 Dao 객체를 호출한다.


예제

@Service("test2.testService") 
//괄호 속 문자열은 식별자를 의미한다.
//괄호를 생략할 경우 클래스명 그대로 사용한다. 
//따라서 ,같은 클래스명이 존재 할 시 같은 식별자가 생성되기때문에 에러가 발생한다.
public class TestService
{
 public String result(int num1, int num2, String oper)
 {
  String str = null;
  
  if(oper.equals("+"))
  {
... 
생략
...
  return str;
 }
} 

@Resouce로 연결

@Resource(name="test2.testService") 
 //name에 필요한 것은 @Service("test2.testService") <- 여기서 괄호 속 문자열, 즉 식별자
 private TestService service; 
        //TestService service = new TestService(); 라고 하는것과 같은 식
 
 @RequestMapping(value="/test2/oper.action", method={RequestMethod.GET})
 public String form() throws Exception
 {
  return "test2/write";
 }

@Repository 


패키지 : org.springframework.stereotype

버젼 : spring 2.0

개요 : 레포지 토리 어노테이션은 일반적으로 DAO에 사용되며 DB Exception을 DataAccessException으로 변환한다.


예제


@Repository("bbs.boardDAO")
public class BoardDAO
{
 private SqlSession sqlSession;
 
 public int insertBoard(Board dto) throws Exception
 {
  ...
 }
}

public class BoardServiceImpl implements BoardService
{
 @Resource(name="bbs.boardDAO")
 private BoardDAO dao;
 
 public int insertBoard(Board dto){}
}


@Controller


패키지 : org.springframework.stereotype

버젼 : spring 2.5

개요 : spring MVC의 Controller 클래스 선언을 단순화시켜준다. 스프링 컨트롤러, 

서블릿을 상속할 필요가 없으며, @Controller로 등록된 클래스 파일에 대한 bean을 자동으로 생성해준다.

 

Controller로 사용하고자 하는 클래스에 @Controller 지정해 주면 component-scan으로 자동 등록된다.

 

- xml 설정



- java


 package han.test;
 
       import org.springframework.stereotype.Controller;
 
       @Controller
       public class SpringC {
       }

@RequestMapping


개요 : RequestMapping annotation은 url을 class 또는 method와 mapping 시켜주는 역활을 한다. annotation을 쓰지 않을때 지정했던 Controller등록을 위한 url bean 설정을 생략 할 수 있다.

class에 하나의 url mapping을 할 경우, class위에 @RequestMapping("/url")을 지정하며

, GET 또는 POST 방식 등의 옵션을 줄 수 있다.

해당되는 method가 실행된 후, return 페이지가 따루 정의되어 있지 않으면 @RequestMapping("/url")에서 

설정된 url로 다시 돌아간다.


수업예제


@RequestMapping(value="/test3/oper.action"[, method=RequestMethod.POST])
public ModelAndView submit(int num1, int num2, String oper) throws Exception
{
 ....
} 

//요청된 URL에 따라 호출될 메서드를 지정한다.
//클라이언트가 /test3/oper.action 을 요청하면 위 메서드가 실행된다는 것이다.
//단, method 지정을 하면 해당 프로토콜에 해당된 요청에만 반응한다.
//여기서 method 는 get/post 둘 다 지정할 수도 있다.
 @RequestMapping(value="/...", method={RequestMethod.GET, RequestMethod.POST})
method=...get || method={...get, ...post}

상세 속성 정보

 (1) value  : "value='/getMovie.do'"와 같은 형식의 매핑 URL 값이다. 디폴트 속성이기 때문에 value만 정의하는 경우에는 'value='은 생략할 수 있다.

 

 예 : @RequestMapping(value={"/addMovie.do", "/updateMovie.do" })

 

이와 같은 경우 "/addMovie.do", "/updateMovie.do" 두 URL 모두 처리한다.

 

(2) method  : GET, POST, HEAD 등으로 표현되는 HTTP Request method에 따라 requestMapping을 할 수 있다. 'method=RequestMethod.GET' 형식으로 사용한다. method 값을 정의하지 않는 경우 모든 HTTP Request method에 대해서 처리한다.

 

예 : @RequestMapping(method = RequestMethod.POST)

 

위의 경우 value 값은 클래스 선언에 정의한 @RequestMapping의 value 값을 상속받는다.  

 

(3) params  : HTTP Request로 들어오는 파라미터 표현이다. 'params={"param1=a", "param2", "!myParam"}' 로 다양하게 표현 가능하다.

 

예 : @RequestMapping(params = {"param1=a", "param2", "!myParam"})

 

위의 경우 HTTP Request에 param1과 param2 파라미터가 존재해야하고 param1의 값은 'a'이어야하며,

myParam이라는 파라미터는 존재하지 않아야한다. 또한, value 값은 클래스 선언에 정의한 @RequestMapping의 value 값을 상속받는다. 

 

(4) headers  : HTTP Request의 헤더 값이다.'headers="someHader=someValue"', 'headers="someHader"', 'headers="!someHader"' 로 다양하게 표현 가능하다. Accept나 Content-Type 같은 헤더에 대해서 media type 표현 시 '*' 도 지원한다.

 

예 : @RequestMapping(value="/movie.do", headers="content-type=text/*")

 

위의 경우 HTTP Request에 Content-Type 헤더 값이 "text/html", "text/plain" 모두 매칭이 된다. 또한,

Type-Level, Method-Level에서 모두 사용할 수 있는데, Type-Level에 정의된 경우, 하위의 모든 핸들러 메소드 에서도 Type-Level에서 정의한 헤더값 제한이 적용된다.


 - 사용 예

@Controller
@RequestMapping("/han/test/*")
public class HelloController
{
@RequestMapping(method=RequestMethod.GET, value="go")
public returntype getMethodName(){
:
}

@RequestMapping(method=RequestMethod.POST, value="go2")
public returntype getMethodName2(){
:
}
}

@Controller("mainController")
@RequestMapping(value="/main.action")
public class MainController {
  
 @RequestMapping(method=RequestMethod.GET)
 public String method() {
  return ".mainLayout";
 }
}
 

@RequestParam


개요 : RequestParam annotation은 key=value 형태로 화면에서 넘어오는 파라미터를 맵핑 된 메소드의

파라미터로 지정해 준다. 주로 get 방식으로 들어오는 request에서 사용한다.

 

아래에서 xxx/editBlog.do?blogId=3 과 같이 접근할 때, editBlogHandler 메소드의 파라미터인 blogId에는 3이 셋팅된다. 필수 요건이 아닐 경우, @RequestParam(value="id", required="false")와 같이 옵션을 주고 사용할 수 있다.


@Controller
      public class BlogController {
 /* 중간생략 */
 
 @RequestMapping("/editBlog")
 public ModelMap editBlogHandler(@RequestParam("blogId") int blogId) {
  blog = blogService.findBlog(blogId); 
  return new ModelMap(blog);
 }
 
 /* 중간생략 */
     }

수업예제


@RequestMapping(value="/...", method={RequestMethod.GET, RequestMethod.POST})
public String submit(HttpServletRequest req
  , @RequestParam(value="num1") int num1
  , @RequestParam(value="num2") int num2
  , @RequestParam(value="oper") String oper) throws Exception
{
 ...  //value : form객체가 넘겨줄 값의 name
}
 
//@RequestParam 어노테이션이 적용된 파라미터는 기본적으로 필수 파라미터이다.
따라서, 명시한 파라미터가 존재하지 않을 경우 400 에러가 발생한다.
 
//여기서 파라미터에 값이 있을수도 없을수도 있는 로직을 구현하려면 다음처럼 작성한다.
 
 
@RequestMapping(value="/...", method={RequestMethod.GET, RequestMethod.POST})
 
public String submit(HttpServletRequest req
  , @RequestParam(value="num1", defaultValue = "0") int num1
  , @RequestParam(value="num2", defaultValue = "0") int num2
  , @RequestParam(value="oper", required=false) String oper) throws Exception
{
 ...
}

@ModelAttribute


개요 : ModelAttribute annotation은 화면의 form 속성으로 넘어온 model을 맵핑된 method의 파라미터로 지정해주는 역활을 한다. 주로 POST 타입으로 넘어오는 form 속성의 model 값을 받아 올 때 사용된다.

(get/post 모두 통용된다.)


 @Controller
     public class BlogController {
 /* 중간생략 */
 
 @RequestMapping("/updateBlog")
 public String updateBlogHandler(@ModelAttribute("blog") Blog blog) {
  blogService.updateBlog(blog);
  return "redirect:findBlogs.do";
 }
 
 /* 중간생략 */
    }

@SessionAttributes


개요 : SessionAttribute annotation은 세션상에서 model의 정보를 유지하고 싶을 경우 사용 할 수 있다.


 @Controller
     @SessionAttributes("blog")
     public class BlogController {
 /* 중간생략 */
 
 @RequestMapping("/createBlog")
 public ModelMap createBlogHandler() {
  blog = new Blog();
  blog.setRegDate(new Date());
  return new ModelMap(blog);
 }
 
 /* 중간생략 */
    }
 

@InitBinder


ο Annotation 기반 Controller 에서 ServletContext 구하기


  :
 
    @Controller
    @RequestMapping("/common/download")
    public class DownloadController {
        @Autowired
        private ServletContext sc;
 
        @RequestMapping
        public ModelAndView download(@RequestParam("filePath") String filePath) throws               Exception              
        {
            String path = sc.getRealPath(filePath);
            return new ModelAndView("common.download", "downloadFile", new File(path));
        }
    }


'Framework > Spring' 카테고리의 다른 글

Spring Framework/ DI / IOC 컨테이너 / POJO  (0) 2013.07.30
Annotation_Spring_MVC_1  (0) 2013.07.29
Annotation  (0) 2013.07.29
Posted by 1+1은?
2013. 7. 29. 16:10

Spring annotation

   spring Framework는 java 5+ 부터 annotaion을 제공 하며, annotation의 사용으로 설정파일을 간결화하고, 객체 또는 메소드의 맵핑을 명확하게 할 수 있다.


목차

@Component 

@Required

@Autowired

@Qualifier

@Resource

@Scope

@PostConstruct

@PreDestroy

@Inject



@Component 


패키지 : org.springframework.stereotype

버젼 : spring 2.5

개요 : <context:component-scan> 태그를 설정파일에 추가하면 해당 어노테이션이 적용된 클래스를 빈으로 등록하게 된다. 범위는 디폴트로 singleton이며 @Scope를 사용하여 지정할 수 있다.

 

설정위치: 클래스 선언부 위 

추가설정 : XML 설정파일에 <context:component-scan>을 정의하고 적용할 기본  패키지를 base-package 속성으로 등록한다.


context:annotation-config 태그는 어노테이션과 관련해서 다음의 BeanPostProcessor를 함께 등록 한다.
           - @Required(RequiedAnnotationBeanPostProcessor)
           - @Autowired(AutowiredAnnotationBeanPostProcessor)
           - @Resource, @PostConstruct, @PreDestory(CommonAnnotationBeanPostProcessor)
           - @Configuration(ConfigurationClassPostProcessor)
 
* 그 외 Repository, Service, Controller 포함



예를 들어 <context:component-scan base-package="xxx" />에서 xxx패키지 하위에서 


@Component로 선언된 클래스를 bean으로 자동 등록한다.

bean의 이름은 해당클래스명(첫글자는 소문자)이 사용된다.       

 

<context:component-scan /> 요소에는 scoped-proxy 속성이 존재 한다. 

scoped-proxy 속성은 <aop:scoped-poxy/> 요소처럼 WebApplicationContext 에서만 유효하며 

"session", "globalSession", "request" 이외의 scope는 무시 되며 아래의 3가지 값을 설정 할 수 있다.

 

 

        no : proxy를 생성하지 않는다.(기본값)

        interfaces : JDK Dynamic Proxy를 이용한 Proxy 생성

        targetClass : 클래스에 대해 프록시를 생성(CGLIB를 이용한 Proxy 생성)

 

 

 -  사용 예


@Component
     @Scope("prototype")   // 생략하면 싱글톤
     public class Test {
            .....
     }


- CGLIB

   기존의 자바 클래스파일로부터 자바의 소스코드를 동적으로 생성하는 라이브러리(자바 소스 변경)

 

http://sourceforge.net/projects/cglib/

 

 

- 스캔 대상 클래스 범위 지정하기

       <context:include-filter> 태그와 <context:exclude-filter> 태그를 사용하면 자동 스캔 대상에 포함시킬 클래스와 포함시키지 않을 클래스를 구체적으로 명시할 수 있다.

 


           
           
      
 


위와 같이 <context:include-filter> 태그와 <context:exclude-filter> 태그는 각각 type 속성과 expresseion 속성을 갖는데, type 속성에 따라 expression 속성에 올 수 있는 값이 달라지는데 type 속성에 입력 가능한 값을 다음과 같다

 

* Type 속성에 올 수 있는 값

 

     annotation : 클랙스에 지정한 어노테이션이 적용됐는지의 여부

            expression 속성에서는 "org.example.SomeAnnotation"와 같은 어노테이션 이름을 입력한다.

      assignable : 클래스가 지정한 타입으로 할당 가능한지의 여부. 

            expression 속성에는 "org.exampleSomeClass" 와 같은 타입 이름을 입력한다.

      regex : 클래스 이름이 정규 표현식에 매칭되는 지의 여부.

           expression 속성에는 "org\.example\.Default.*" 와 같이 정규표현식을 입력한다.

      aspectj : 클래스 이름이 AspectJ 의 표현식에 매칭되는 지의 여부.

          expression 속성에는 "org.example..*Service+" 와 같이 AspectJ 의 표현식을 입력한다.

 

 

@Required 

 

패키지 : org.springframework.beans.factory.annotation

버젼 : spring 2.0

Required 어노테이션은 필수 프로퍼티임을 명시하는 것으로 필수 프로퍼티를 설정하지 않을 경우 

빈 생성시 예외를 발생시킨다.


설정위치 : setter 메소드

추가설정 

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" /> 클래스를 빈으로 등록시켜줘야 한다. 

해당 설정 대신에<context:annotation-config> 태그를 사용해도 된다.

 

    - 1단계 : 코드내에 프로퍼티 설정 메소드에 @Required 어노테이션을 붙인다.


import org.springframework.beans.factory.annotation.Required
     public class TestBean {
         private TestDao testDao;
  
         @Required
         public void setTestDao(TestDao testDao) {
            this.testDao = testDao;
         }
     }


- 2단계 : 스프링 설정 파일에 RequiredAnnotationBeanPostProcessor 클래스를 빈으로 등록



 
    
          

    


RequiredAnnotationBeanPostProcessor 클래스는 스프링 컨테이너에 등록된 bean 객체를 조사하여 @Required 어노테이션으로 설정되어 있는 프로퍼티의 값이 설정되어 있는지 검사하고 설정되어있지 않으면 bean 생성시 예외를 발생시킨다.

 

     RequiredAnnotationBeanPostProcessor 클래스를 빈으로 등록하지 않고

     <context:annotation-config> 다음과 같이 태그를 이용할 수도 있다.



     

       

     


@Autowired  

 

 패키지 : org.springframework.beans.factory.annotation

버젼 : spring 2.5

개요 : 오토 와이어링 어노테이션은 의존관계를 자동설정할 때 사용하며 타입을 이용하여 의존하는 객체를 삽입해 준다. 그러므로 해당 타입의 빈객체가 존재하지 않거나 또는 2개 이상 존재할 경우 스프링은 예외를 발생시키게 된다.


설정 위치 : 생성자, 필드, 메소드(setter메소드가 아니여도 된다)

추가설정 : <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.


옵션 : required - @Autowired어노테이션을 적용한 프로퍼티에 대해 설정할 필요가 없는 경우에 false값을 주며 이때 해당 프로퍼티가 존재하지 않더라도 스프링은 예외를 발생시키지 않는다.

 

@Autowired(required=false)로 선언한다. (기본값은 true)

 


특징 : byType으로 의존관계를 자동으로 설정할 경우 같은 타입의 빈이 2개 이상 존재하게 되면 예외가 발생하는데, Autowired도 이러한 문제가 발생한다. 이럴 때 @Qualifier를 사용하면 동일한 타입의 빈 중 특정 빈을 사용하도록 하여 문제를 해결할 수 있다.

 

       @Autowired

       @Qualifier("test")

       private Test test;

 


@Qualifier


패키지 : org.springframework.beans.factory.annotation

버젼 : spring 2.5

개요 : 콸리파이어 어노테이션은 @Autowired의 목적에서 동일 타입의 빈객체가 존재시 특정빈을 삽입할 수 있게 설정한다. @Qualifier("mainBean")의 형태로 @Autowired와 같이 사용하며 해당 <bean>태그에 <qualifire value="mainBean" /> 태그를 선언해주어야 한다. 메소드에서 두개이상의 파라미터를 사용할 경우는 파라미터 앞에 선언해야한다.


설정위치 : @Autowired 어노테이션과 함께 사용된다.

추가설정 : 동일타입의 빈객체 설정에서 <qualifier value="[alias명]" />를 추가해 준다.

옵션 : name - alias명



  
  
  
 
 
 

 

@Resource 


개요 : 자바 6버전 및 JEE5 버전에 추가된 것으로 어플리케이션에서 필요로 하는 자원을 자동 연결할 때 사용 한다. 스프링 2.5 부터 지원하는 어노테이션으로 스프링에서는 의존하는 빈 객체를 전달할 때 사용하다.

              @Autowired 와 같은 기능을 하며 @Autowired와 차이점은 @Autowired는 타입으로(by type),  @Resource는 이름으로(by name)으로 연결시켜준다는 것이다.


설정위치 : 프로퍼티, setter 메소드


추가설정 : <bean class="org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor"/> 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.

옵션 : name 

      name속성에 자동으로 연결될 빈객체의 이름을 입력한다.

      @Resource(name="testDao")

 

CommonAnnotationBeanPostProcessor 클래스를 설정파일에 빈객체로 등록하여 어노테이션을 적용시킨다.



 
    
          

    


예제


public class UserService
{
        @Resource(name="user2")
 private User user;  
        //UserImpl user2 = new UserImpl();
        //User user = user2;

 public void setUser(User user)
 {
  this.user = user;
 }
 public String result()
 {
  return user.getData();
 }
}


@Scope 


패키지 : org.springframework.beans.factory.annotation

개요 : 스프링은 기본적으로 빈의 범위를 "singleton" 으로 설정한다. "singleton" 이 아닌 다른범위를 지정하고 싶다면 @Scope 어노테이션을 이용하여 범위를 지정한다.

설정 : prototype, singleton, request, session, globalSession

 

사용 예 - 1


@Component
     @Scope(value="prototype")
     public class Worker {
            :
     }
 


사용 예 - 2


@Component
    @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
    public class Worker {
           :
    }


 

@PostConstruct, @PreDestroy, @Inject 


@PostConstruct

패키지 : javax.annotation

버젼 : jdk1.6, spring 2.5

개요 : 의존하는 객체를 설정한 이후에 초기화 작업을 수행하기 위해 사용

설정위치 : 초기화 작업 수행 메소드

추가설정 : CommonAnnotationBeanPostProcessor 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.


-예제


@PostConstruct
 public void init()
 {
  System.out.println("객체 생성 후 내가 먼저 실행된다.");
 }



@PreDestroy

패키지 : javax.annotation

버젼 : jdk1.6, spring 2.5

개요 : 컨테이너에서 객체를 제거하기 전에 해야할 작업을 수행하기 위해 사용

설정위치 : 해당 작업 메소드

추가설정 : CommonAnnotationBeanPostProcessor 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.

 

@Inject

개요 : JSR-330 표준 Annotation으로 Spring 3 부터 지원하는 Annotation이다. 특정 Framework에 종속되지 않은 어플리케이션을 구성하기 위해서는 @Inject를 사용할 것을 권장한다. @Inject를 사용하기 위해서는 클래스 패스 내에 JSR-330 라이브러리인 javax.inject-x.x.x.jar 파일이 추가되어야 함에 유의해야 한다. 


'Framework > Spring' 카테고리의 다른 글

Spring Framework/ DI / IOC 컨테이너 / POJO  (0) 2013.07.30
Annotation_Spring_MVC_2  (0) 2013.07.29
Annotation  (0) 2013.07.29
Posted by 1+1은?