03. Spring Framework
728x90

@Controller

@Service

@Repository - Dao

=> @Component - 모두 다 쓸 수 있지만 보통 Dto를 정의할 때 쓴다

Main

public class HelloMain {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("주소/application.xml"); 
		HelloMessage helloMessage = context.getBean("id1", HelloMessageKor.class);
		
		String greeting = helloMessage.hello("이름");
	}
}

Bean

//application.xml

<bean id="id1" class=""></bean>
	<property name="dao" ref="id2"></property> //ref가 id2이므로 id2 먼저 호출
<bean id="id2" class=""></bean>

//Dao

public class TestDao {
	public TestDao() {}
	
	public String getName() {
		return "이름";
	}
}

//Service

	private TestDao dao;
	
	public void setDao(TestDao dao) {
		this.dao = dao;
	}
    
    public String hello(String name) {
		//dto를 만들어 주지 않았음에도 사용 가능 >> 스프링에서 자동으로 생성해 줌
        name = dao.getName();
	}

Context

application - Namespaces - context 선택

//application.xml

<context:component-scan base-package="파일 위치"></context:component-scan>

//Dao

import org.springframework.stereotype.Component;

@Component(t2)
public class TestDao {
	public TestDao() {}
	
	public String getName() {
		return "이름";
	}
}

//Service

import org.springframework.stereotype.Component;

@Component(value="id1")
public class HelloMessageKor implements HelloMessage {
	
    // setter 없애고 설정
    // 객체가 하나밖에 없을 때는 쓰지 않아도 된다
    @Autowired
    // dao 타입이 겹칠 때 이름을 설정해 줘야 한다
    // web을 만들 때 일반적으로는 공통적으로 설정하지 않아서 필요없음
    @Qualifier(value = "t2dao")
	private TestDao dao;

	public HelloMessageKor() {}

	public String hello(String name) {
		name = dao.getName();
	}
	
}

 

728x90

'프로그래밍 > SPRING' 카테고리의 다른 글

06. AOP  (0) 2022.04.26
05. DI 적용  (0) 2022.04.24
04. DI  (0) 2022.04.23
02. IoC & Container  (0) 2022.04.17
01. Spring  (0) 2022.04.12