일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- 자바의정석
- 정보처리기사실기요약
- 타입스크립트
- 코딩테스트
- javascript
- 정보처리기사실기
- php
- 정보처리기사실기정리
- Java의정석
- spring
- Oracle
- typescript
- ReactNative
- 이안의평일코딩
- 국비코딩
- VUE
- 자바스크립트
- CSS
- react
- 정보처리기사정리
- 자스코테
- 리액트
- 정보처리기사
- 정보처리기사요약
- 자바스크립트 코딩테스트
- 리액트네이티브
- 평일코딩
- 오라클
- 국비IT
- 스프링
- Today
- Total
이안의 평일코딩
Spring 3일차 - Container 본문
2020.10.22(목)
1. Container : 여러개의 클래스를 모아서 관리 영역
========
ApplicationContext (스프링 4)
==> XML을 파싱
AnnotationConfigApplicationContext (스프링 5)
==> Annotation 이용
xml 이용 (스프링4)
src/main/java
com.sist.di
Sawon.java
package com.sist.di;
public class Sawon {
private String name;
private String dept;
private String job;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
Member.java
package com.sist.di;
public class Member {
private String name;
private String addr;
private String tel;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
app1.xml (beans, p)
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sa" class="com.sist.di.Sawon"
p:name="홍길동"
p:dept="영업부"
p:job="대리"
/>
</beans>
app2.xml (beans, p)
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mem" class="com.sist.di.Member"
p:name="심청이"
p:addr="서울"
p:tel="010-1111-1111"
/>
</beans>
MainClass.java
package com.sist.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
String[] xml= {"app1.xml", "app2.xml"};
ApplicationContext app=new ClassPathXmlApplicationContext(xml);
// new ClassPathXmlApplicationContext({"app1.xml", "app2.xml"});
Sawon sa = (Sawon)app.getBean("sa"); // Object => 반드시 형변환
// DL => id명을 가지고 클래스를 찾아주는 기능
System.out.println("이름:"+sa.getName());
System.out.println("부서:"+sa.getDept());
System.out.println("직위:"+sa.getJob());
Member mem = app.getBean("mem",Member.class); // 데이터을 통일 (제네릭스)
// List<String> 모든 데이터형이 object에서 string으로 변환
System.out.println("이름:"+mem.getName());
System.out.println("주소:"+mem.getAddr());
System.out.println("전화:"+mem.getTel());
}
}
@Configuration 애노테이션 (스프링5)
com.sist.di
Config.java
package com.sist.di;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean("sawon")
public Sawon sawonInfo() {
/*
* <bean id="sa" class="com.sist.di.Sawon"
p:name="홍길동"
p:dept="영업부"
p:job="대리"
/>
* map.put("sa", new Sawon()) => 100번지
* public Object getBean(String id){
* return map.get(id);
* }
* Sawon sa=getBean("sa")
* Sawon sa=100
*/
Sawon s = new Sawon(); //객체 생성
// DI
s.setName("이순신");
s.setDept("개발부");
s.setJob("과장");
return s;
}
}
Config2.java
package com.sist.di;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config2 {
@Bean("mem")
public Member memberInfo() {
Member m=new Member();
m.setName("춘향이");
m.setAddr("서울");
m.setTel("010-1111-1111");
return m;
}
}
MainClass2.java
package com.sist.di;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Config.class, Config2.class);
Sawon s=(Sawon)app.getBean("sawon");
System.out.println(s.getName());
System.out.println(s.getDept());
System.out.println(s.getJob());
Member m=(Member)app.getBean("mem");
System.out.println(m.getName());
System.out.println(m.getAddr());
System.out.println(m.getTel());
}
}
=========================================
2. 자동주입 @Autoweired 애노테이션
src/main/java
Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.sist.di2.EmpVO" alias="empVO"/>
</typeAliases>
<mappers>
<mapper resource="com/sist/di2/emp-mapper.xml"/>
</mappers>
</configuration>
app3.xml (beans, context, p)
<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 데이터베이스 정보 생성
BasicDataSource
driverClassName
url
username
password
-->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="oracle.jdbc.driver.OracleDriver"
p:url="jdbc:oracle:thin:@211.238.142.000:1521:XE"
p:username="hr"
p:password="happy"
/>
<!--
1. 일반 데이터 값주입
2. 스프링에서 생성된 객체 주소 주입 p:객체명-ref="해당 클래스의 id명"
-->
<!-- SqlSessionFactory (ssf) 오라클정보 getConnection-->
<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="ds"
p:configLocation="classpath:Config.xml"
/>
<!-- EmpDAO로 전송 -->
<bean id="dao" class="com.sist.di2.EmpDAO"
p:sqlSessionFactory-ref="ssf"
/>
</beans>
* lombok-1.18.12.jar (VO Getter/Setter자동생성)
mvnrepository.com/artifact/org.projectlombok/lombok/1.18.12
com.sist.di2
EmpVO.java
package com.sist.di2;
import java.util.*;
import lombok.Getter;
import lombok.Setter;
// VO => 스프링에서 관리하는 클래스가 아니다 (데이터) : 사용자 정의 데이터형
/*
* 스프링이 관리하는 대상
* =================
* @Repository
* 1. DAO
*
* @Component
* 2. Manager (웹크롤링, 트위터, openApi)
*
* @Controller
* 3. Model
*
* @Service
* 4. Service (DAO+DAO) => BI
*
* @Aspect
* 5. AOP(공통모듈)
*/
@Getter
@Setter
public class EmpVO {
private int empno;
private String ename;
private String job;
private Date regdate;
private int sal;
}
emp-mapper.xml (Mybatis이용) => 환경설정위해서 Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sist.di2.emp-mapper">
<select id="empListData" resultType="EmpVO">
SELECT empno,ename,job,hiredate as regdate,sal
FROM emp
</select>
</mapper>
EmpDAO.java
package com.sist.di2;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.*;
public class EmpDAO extends SqlSessionDaoSupport{
public List<EmpVO> empListData(){
return getSqlSession().selectList("empListData");
}
}
MainClass.java
package com.sist.di2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.*;
public class MainClass {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("app3.xml");
// EmpDAO dao=new EmpDAO(); =>new를주면 setting이 안되서 오류가 남.
// 스프링에서 생성된 DAO를 가져와야함
EmpDAO dao=(EmpDAO)app.getBean("dao");
List<EmpVO> list=dao.empListData();
for(EmpVO vo:list) {
System.out.println(vo.getEmpno()+" "
+vo.getEname()+" "
+vo.getJob()+" "
+vo.getRegdate().toString()+" "
+vo.getSal());
}
}
}
*아래와 같이 dataSource로부터 databaseId를 찾을 수 없다고 오류가 뜨면
ERROR: org.apache.ibatis.executor.BaseExecutor - Could not get a databaseId from dataSource
org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'
Project 오른쪽클릭 - Properties를 클릭한 후
Java Build Path-Libraries-Add Eternal JARs을 통해 ojdbc6.jar를 넣어주면 오류가 안뜬다!
(Referenced Libraries로 복붙해도 된다)
=>출력 결과
====================================================================================================
'Back-end > Spring' 카테고리의 다른 글
Spring 6일차 - ComponentScan (0) | 2020.10.31 |
---|---|
Spring 5일차 - Repository (0) | 2020.10.31 |
Spring 4일차 - Autowired (0) | 2020.10.23 |
Spring 2일차 - XML, Configuration (0) | 2020.10.21 |
Spring 1일차 - DI(Dependency Injection 의존성 주입) (0) | 2020.10.20 |