단순 시 뮬 레이 션 spring di

spring di (즉 주입 에 의존 하 는 것) 의 원리 에 대한 개인 적 인 이 해 는 이 렇 습 니 다. 설정 파일 을 먼저 읽 고 xml 를 분석 하여 유용 한 정 보 를 추출 한 다음 에 반사 체 제 를 통 해 클래스 나 방법의 정례 화 를 실현 합 니 다.
오늘 저 는 두 가지 주입 방식 을 모 의 했 습 니 다. 하 나 는 bean 을 주입 하 는 것 이 고 다른 하 나 는 factory 를 주입 하 는 것 입 니 다. 공장 모델 에 대해 저 는 괜 찮 은 것 같 습 니 다. 구 조 를 구축 하면 관리 가 쉬 울 것 같 습 니 다.그리고 bridge 모델 은 개발 중 에 도 관리 하기 편 합 니 다.그래서 나 는 이 작은 예 에서 bridge 와 factory 모델 을 결합 시 켰 다.
다음은 코드:
1, UserDao: 인터페이스

public interface UserDao {

	public boolean add();
	
}


2, ImplUserDaoMySql: UserDao 인 터 페 이 스 를 실현 하 는 MySql 데이터베이스 dao 층

public class ImplUserDaoMySql implements UserDao {

	@Override
	public boolean add() {
		System.out.println("add MySql Dao!");
		return true;
	}

}

3, ImplUserDaoOracle: UserDao 인 터 페 이 스 를 실현 하 는 Oracle 데이터베이스 dao 층

public class ImplUserDaoOracle implements UserDao {

	@Override
	public boolean add() {
		System.out.println("add Oracle Dao!");
		return true;
	}

}

위의 두 개 는 다리 모델 의 장점 을 나 타 낼 수 있다.
4. DaoFactory: 공장 모델 류 는 각종 UserDao 를 생산 하 는 데 사용 된다.

public class DaoFactory {

	public static UserDao getUserDaoOracle(){
		return new ImplUserDaoOracle();
	}
	
	public static UserDao getUserDaoMySql(){
		return new ImplUserDaoMySql();
	}
}

5, AnalogapplicationContext: 아 날로 그 di 메 인 프로그램

public class AnalogApplicationContext {
	private Map<String, Object> map = new HashMap<String, Object>();

	public AnalogApplicationContext(String configLocation) {
		//       ,     map 
		SAXReader sax = new SAXReader();

		try {
			Document document = sax.read(AnalogApplicationContext.class
					.getResourceAsStream(configLocation));
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (int i = 0; i < elements.size(); i++) {
				Element element = elements.get(i);
				String idDI = element.attribute("id").getData().toString();
				String classDI = element.attribute("class").getData()
						.toString();
				String factoryMethodDI = "";
				if (element.attribute("factory-method") == null) {
					map.put(idDI, Class.forName(classDI).newInstance());
				} else {
					factoryMethodDI = element.attribute("factory-method")
							.getData().toString();
					Object obj = Class.forName(classDI).newInstance()
							.getClass().getDeclaredMethod(factoryMethodDI)
							.invoke(Class.forName(classDI).newInstance());
					map.put(idDI, obj);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Object getBean(String id) {
		return map.get(id);
	}
}

6. applicationContext - di. xml: spring 시 뮬 레이 션 프로필 입 니 다. 이 시 뮬 레이 션 프로그램 에서 applicationContext - di. xml 는 AnalogapplicationContext. java 메 인 시 뮬 레이 션 프로그램 과 같은 디 렉 터 리 에 두 어야 합 니 다. applicationContext - di. xml 파일 경 로 를 가 져 오 려 면 먼저 AnalogapplicationContext. java 를 통 해 가 져 와 야 합 니 다. 물론 이것 도 가 변 적 이 고 자 유 롭 게 발휘 해 야 합 니 다.

<?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:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	
	<bean id="userDaoOracle" class="com.fairy.spring.di.impldao.ImplUserDaoOracle" />	
	<bean id="userDaoMySql" class="com.fairy.spring.di.daofactory.DaoFactory" factory-method="getUserDaoMySql" />
	
</beans>

7, TestDI: 테스트 클래스, 두 가지 주입 방식 을 테스트 합 니 다.

public class TestDI {

	/**
	 * @    spring DI  
	 */
	public static void main(String[] args) {
		/**
		 *   bean    
		 */
		AnalogApplicationContext alAcOracle = new AnalogApplicationContext("applicationContext-di.xml");
		UserDao userdaoOracle = (UserDao)alAcOracle.getBean("userDaoOracle");
		userdaoOracle.add();
		/**
		 *   factory    
		 */
		AnalogApplicationContext alAcMySql = new AnalogApplicationContext("applicationContext-di.xml");
		UserDao userdaoMySql = (UserDao)alAcMySql.getBean("userDaoMySql");
		userdaoMySql.add();
	}

}


좋은 웹페이지 즐겨찾기