티스토리 뷰


 @Component("이름") 마크를 달아 놓으면

 xml의 빈으로 등록 해달라는 표시 id는 기본적으로 클래스면의 첫글자를 소문자로




예제


java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package di03;
 
import org.springframework.stereotype.Component;
 
@Component("rooobot")
public class Robot {
    private MissileAttack attack = new MissileAttack();
    
    public void fight(){
        System.out.println("로봇이 공격을 합니다.");
        attack.attack();
    }
}
 
cs


xml


context를 체크해야 어노테이션 사용 가능


1
2
3
4
5
6
7
8
9
10
11
<?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"
    xsi:schemaLocation="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.1.xsd">
 
    <context:component-scan base-package="di03"/>    
    
</beans>
 
cs

component-scan을 통해 @Component 된걸 모두 찾음



사용 법

1
2
3
4
5
6
7
8
public class Kid {
    public static void main(String[] args) {
        ApplicationContext context = new GenericXmlApplicationContext("di03/applicationContext.xml");
        
        Robot robot = (Robot) context.getBean("rooobot");
        robot.fight();
    }
}
cs


반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함