단순 시 뮬 레이 션 spring di
오늘 저 는 두 가지 주입 방식 을 모 의 했 습 니 다. 하 나 는 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();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.