의존객체
6강 DI(Dependency Injection)
6-1 : DI(Dependency Injection)란?
배터리 분리형으로 생각해보자.
6-2 : 스프링 DI설정 방법
public class MainClass {
public static void main(String[] args) {
String[] sNums = {"H39r8djakndfae32", "H39asdfaelu42o23", "H39iiemamca8w9h4",
"H39lkmn754fghia7", "H39plo865cuy8k92", "H39mnbviiaed89q1",
"H399omjjyv56t3d5", "H39lczaqwg644gj8", "H39ymbcsh74thgh2",
"H39lesvj7544vf89"};
String[] sIds = {"rabbit", "hippo", "raccoon", "elephant", "lion",
"tiger", "pig", "horse", "bird", "deer"};
String[] sPws = {"96539", "94875", "15284", "48765", "28661",
"60915", "30028", "29801", "28645", "28465"};
String[] sNames = {"agatha", "barbara", "chris", "doris", "elva",
"fiona", "holly", "jasmin", "lena", "melissa"};
int[] sAges = {19, 22, 20, 27, 19, 21, 19, 25, 22, 24};
String[] sGenders = {"M", "W", "W", "M", "M", "M", "W", "M", "W", "W"};
String[] sMajors = {"English Literature", "Korean Language and Literature",
"French Language and Literature", "Philosophy", "History",
"Law", "Statistics", "Computer", "Economics", "Public Administration"};
StudentAssembler assembler = new StudentAssembler();
StudentRegisterService registerService = assembler.getRegisterService();
for (int j = 0; j < sNums.length; j++) {
Student student = new Student(sNums[j], sIds[j], sPws[j], sNames[j],
sAges[j], sGenders[j], sMajors[j]);
registerService.register(student);
}
StudentModifyService modifyService = assembler.getModifyService();
modifyService.modify(new Student("H39lesvj7544vf89", "deer", "00000", "melissa",
26, "W", "Vocal Music"));
StudentSelectService selectService = assembler.getSelectService();
Student modifiedStudent = selectService.select("H39lesvj7544vf89");
System.out.print("sNum:" + modifiedStudent.getsNum() + "\t");
System.out.print("|sId:" + modifiedStudent.getsId() + "\t");
System.out.print("|sPw:" + modifiedStudent.getsPw() + "\t");
System.out.print("|sName:" + modifiedStudent.getsName() + "\t");
System.out.print("|sAge:" + modifiedStudent.getsAge() + "\t");
System.out.print("|sGender:" + modifiedStudent.getsGender() + "\t");
System.out.print("|sMajor:" + modifiedStudent.getsMajor() + "\n\n");
StudentAllSelectService allSelectService = assembler.getAllSelectService();
Map<String, Student> allStudent = allSelectService.allSelect();
Set<String> keys = allStudent.keySet();
Iterator<String> iterator = keys.iterator();
자바 MainClass에서 new 키워드를 사용해서 StudentAssembler 객체를 생성하고, 생성된 assembler객체를 통해 registerService, modifyService 등의 기능을 실행한다.
StudentAssembler 클래스에서는
public class StudentAssembler {
private StudentDao studentDao;
private StudentRegisterService registerService;
private StudentModifyService modifyService;
private StudentDeleteService deleteService;
private StudentSelectService selectService;
private StudentAllSelectService allSelectService;
public StudentAssembler() {
studentDao = new StudentDao();
registerService = new StudentRegisterService(studentDao); //주입. 생성을 할 때, Dao객체를 하나 만들어서 다른 객체 생성할때 다 주입해줌
modifyService = new StudentModifyService(studentDao);
deleteService = new StudentDeleteService(studentDao);
selectService = new StudentSelectService(studentDao);
allSelectService = new StudentAllSelectService(studentDao);
}
....
7강 다양한 의존 객체 주입
7-1 생성자를 이용한 의존 객체 주입
자바에서 아래 코드를
public StudentRegisterService(StudentDao studentDao) {
this.studentDao = studentDao;
}
xml파일에서 이렇게 작성
<bean id="studentDao" class="ems.member.dao.StudentDao" ></bean>
<bean id="registerService" class="ems.member.service.StudentRegisterService">
<constructor-arg ref="studentDao" ></constructor-arg>
</bean>
7-2 setter를 이용한 의존 객체 주입
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public void setUserId(String userId) {
this.userId = userId;
}
-->
<bean id="dataBaseConnectionInfoDev" class="ems.member.DataBaseConnectionInfo">
<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="userId" value="scott" />
</bean>
7-3 List타입 의존 객체 주입
public void setDevelopers(List<String> developers) {
this.developers = developers;
}
-->
<property name="developers">
<list>
<value>Cheney.</value>
<value>Eloy.</value>
<value>Jasper.</value>
<value>Dillon.</value>
<value>Kian.</value>
</list>
</property>
7-4 Map타입 객체 주입
public void setAdministrators(Map<String, String> administrators) {
this.administrators = administrators;
}
-->
<property name="administrators">
<map>
<entry>
<key>
<value>Cheney</value>
</key>
<value>cheney@springPjt.org</value>
</entry>
<entry>
<key>
<value>Jasper</value>
</key>
<value>jasper@springPjt.org</value>
</entry>
</map>
</property>
8강 스프링 설정 파일 분리
8-1 스프링 설정 파일 분리
보통 dao/서비스객체/db관련 객체/나머지 이런식으로 기능별로 분리한다.
그리고 분리한 설정 파일을 모아서 스프링 컨테이너를 만들어준다. 스프링 컨테이너를 만들 때는 배열을 이용해서 넣어준다.
8-2 빈(Bean)의 범위
- 싱글톤(Singleton)
스프링 컨테이너에서 생성된 빈(Bean)객체의 경우 동일한 타입에 대해서는 기본적으로 한 개만 생성이 되며, getBean() 메소드로 호출될 때 동일한 객체가 반환된다.
- 프로토타입(Prototype)
싱글톤 범위와 반대의 개념도 있는데 이를 프로토타입(Prototype) 범위라고 한다. 프로토타입의 경우 개발자는 별도로 설정을 해줘야 하는데, 스프링 설정 파일에서 빈 (Bean)객체을 정의할 때 scope속성을 명시해 주면 된다.
<bean id="dependencyBean" class="scope.ex.DependencyBean">을
<bean id="dependencyBean" class="scope.ex.DependencyBean" scope="prototype">로 수정
9강 의존객체 자동 주입
9-1 의존객체 자동 주입이란?
스프링 설정 파일에서 의존 객체를 주입할 때 <constructor-org> 또는 <property>태그로 의존 대상 객체를 명시하지 않아도 스프링 컨테이너 가 자동으로 필요한 의존 대상 객체를 찾아서 의존 대상 객체가 필요한 객체에 주입해 주는 기능이다.
구현 방법은 @Autowired와 @Resource 어노테이션을 이용해서 쉽게 구현할 수 있다.
9-2 : @Autowired
주입하려고 하는 객체의 타입이 일치하는 객체를 자동으로 주입해준다. 프로퍼티, 생성자, 메소드에 모두 넣을 수 있다.
주의할 점은 property나 메소드에 넣으려면 디폴트 생성자를 하나 꼭 명시해주어야 한다.
(생성자에 @Autowired 통해서 자동주입하려면 상관X)
public class WordRegisterService {
@Autowired //appCtx.xml에서 설정해주진 않았지만 자동으로 찾아주라고 스프링 컨테이너에 요청
private WordDao wordDao;
public WordRegisterService() {
}
public WordRegisterService(WordDao wordDao) { //그래서 자동으로 wordDao타입을 찾아서 넣어줌
this.wordDao = wordDao;
}
....
9-3 : @Resource
주입하려고 하는 객체의 이름이 일치하는 객체를 자동으로 주입한다. 생성자에는 못쓰고 프로퍼티나 메소드에만 쓸 수 있다. 그러므로 디폴트 생성자를 명시해주어야 한다.
10강 의존객체 선택
10-1 의존객체 선택
동일한 객체가 2개 이상인 경우 스프링 컨테이너는 자동 주입 대상 객체를 판단할 수 없어서 Exception을 발생시킨다.
-->@Qualifier어노테이션을 사용한다.
자바에서
@Autowired
@Qualifier("usedDao")
private WordDao wordDao;
xml파일에서
<bean id="wordDao" class="com.word.dao.WordDao" >
<qualifier value="usedDao"/>
</bean>
<bean id="wordDao2" class="com.word.dao.WordDao" />
<bean id="wordDao3" class="com.word.dao.WordDao" />
10-2 의존객체 자동 주입 체크
required==false 이거는 거의 안쓰인데..
10-3 @Injection
@Inject
@Named(value="wordDao1")을 넣어준다.
'Spring' 카테고리의 다른 글
220114 자바 스프링 프레임워크 - 설정 및 구현 (0) | 2022.01.14 |
---|---|
220113 자바 스프링 프레임워크 - 스프링 프레임워크, 프로젝트 생성 (0) | 2022.01.13 |