package com.model.di.exam08;
public interface ShopService {
void write(Shopping shop);
}
2) 서비스 클래스
package com.model.di.exam08;
public class ShopServiceImpl implements ShopService {
private ShopDao shopDao;
public void setShopDao(ShopDao shopDao){
this.shopDao = shopDao;
}
@Override
public void write(Shopping shop) {
// TODO Auto-generated method stub
System.out.println("ShopServiceImpl.write() - 1. 서비스 제공");
shopDao.insert(shop);
}
}
3) DAO 인터페이스
package com.model.di.exam08;
public interface ShopDao {
void insert(Shopping shop);
}
6) 실행 클래스
package com.model.di.exam08;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/*
* 1. interface를 적용한 db 연동
* 2. byName : 프로퍼티 이름과 동일한 객체 주입
* Main -> Service -> Dao -> Shopping
*/
public static void main(String[] args) {
AbstractApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext2.xml");
context.registerShutdownHook();
/*
*빈 객체의 이름이나 타입을 이용하여 의존 객체를 자동으로 주입할 수 있다.
* byName: 프로퍼티 이름과 동일한 이름의 빈 객체를 주입.
* byType: 프로퍼티 타입과 동일한 타입을 가진 빈 객체를 주입.
* constructor: 생성자 파라미터 타입과 동일한 타입을 갖는 빈 객체를 생성자에 전달
*/
ShopService shopService = (ShopService)context.getBean("shopService");
shopService.write(new Shopping());
context.close();
}
}
7) 설정파일
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- exam08 예제 : 프로퍼티 이름을 이용한 의존 관계 자동 설정 -->
<!-- 1) 프로퍼티 name으로 객체 넘기는 방식
<bean id="shopService" class="com.model.di.exam08.ShopServiceImpl">
<property name="shopDao" ref="shopDao"></property>
</bean>-->
<!-- 2) autowire에 byName은 프로퍼티 이름과 동일한 빈 객체 이름을 찾아 주입하는 방식 -->
<bean id="shopService" class="com.model.di.exam08.ShopServiceImpl" autowire="byName"/>
<bean id="shopDao" class="com.model.di.exam08.ShopDaoImpl"></bean>
<!-- bean id shopDao와 ShopDaoImple에 있는 setShopDao가 동일 -->
</beans>
' Spring Framework' 카테고리의 다른 글
스프링에서 Bean 객체의 플로우를 보기 위한 예제 (0) | 2016.03.29 |
---|---|
Bean 객체의 타입을 이용하여 의존 객체를 주입 (autowire="byType") (0) | 2016.03.28 |
List 타입과 Map 타입 프로퍼티 전달 받기 (0) | 2016.03.28 |
생성자를 이용하여 자료를 전달 (constructor-arg) (0) | 2016.03.28 |
스키마 p(namespaces)를 이용한 값 전달 (0) | 2016.03.28 |