1. String Container가 어떻게 일할 지를 설정하는 파일 - Spring container는 설정파일에 설정된 내용을 읽어 Application에서 필요한 기능들을 제공한다.
2. XML기반으로 작성한다.
3. Root tag는 <beans> 이다
4. 파일명은 상관없다.
예) applicationContext.xml <?xml version = "1.0" encoding="utf-8"> <beans 설정></beans>
* Bean 객체 주입 받기
1. 주입 할 객체를 설정파일에 설정한다. - <bean> : 스프링컨테이너가 관리할 Bean객체를 설정 - 기본 속성 - name : 주입 받을 곳에서 호출 할 이름 설정 - id : 주입 받을 곳에서 호출할 이름 설정('/' 값으로 못 가짐) - class : 주입할 객체의 클래스 - factory-method : 객체를 생성해 주는 factory메소드 호출 시 -> 주로 싱글턴 패턴 구현 클래스 객체 호출 시
- 객체간의 의존관계를 객체 자신이 아닌 외부의 조립기가 수행한다. - 제어의 역할 이라는 의미로 사용되었음. - Martin Fowler, 2004 - 제어의 어떠한 부분이 반전되는가라는 질문에 '의존 관계 주입'이라는 용어를 사용 - 복잡한 어플리케이션은 비지니스 로직을 수행하기 위해서 두 개 이상의 클래스들이 서로 협업을 하면서 구성됨. - 각각의 객체는 협업하고자 하는 객체의 참조를 얻는 것에 책임성이 있음. - 이 부분은 높은 결합도와 테스트하기 어려운 코드를 양산함 - DI를 통해 시스템에 있는 각 객체를 조정하는 외부 개체가 객체들에게 생성시에 의존관계를 주어짐 - 즉, 의존이 객체로 주입됨 - 객체가 협업하는 객체의 참조를 어떻게 얻어낼 것인가라는 관점에서 책임성의 역행임 - 느슨한 결함이 주요 강점 - 객체는 인터페이스에 의한 의존관계만을 알고 있으며, 이 의존관계는 구현 클래스에 대한 차이를 모르는 채 서로 다른 구현으로 대체가 가능
- Rod Johnson 창시 - Expert one-on-one J2EE Design - Development, 2002, Wrox - Expert one-on-one J2EE Development without EJB, 2004, Wrox - 엔터프라이즈 어플리케이션 개발의 복잡성을 줄여주기 위한 목적(종속적이지 않은 목적) - EJB 사용으로 수행되었던 모든 기능을 일반 POJO(Planin Old Java Object)를 사용해서 가능하게 함. - 경량 컨테이너(light weight container) - www.springframework.org
2. 주요 개념
- 의존성 주입(Dependency InJection) - 관점 지향 프로그래밍
3. Spring의 장점
- 경량 컨테이너 - 객체의 라이프 사이클 관리, Java EE구현을 위한 다양한 API제공 - DI(Dependency Injection)지원 - AOP(Aspect Oriented Programming) 지원 - POJO (Plain Old Java Object) 지원 - 다양한 API와의 연동 지원을 통한 Java EE 구현 가능
public static void main(String[] args)throws Exception { DepartmentDTO deptDTO = new DepartmentDTO(); deptDTO.setDepartmentId("D0001"); EmployeeDTO empDTO = new EmployeeDTO("00013", "김건모", "abc@abc.com", "과장", 403000, deptDTO); EmployeeDAO dao = EmployeeDAO.getInstance();
// dao.insertEmployee(empDTO); empDTO.setSalary(5405050); empDTO.setJobPosition("부장"); int cnt = dao.updateEmployee(empDTO); System.out.println("변경된 row 수 : "+cnt); cnt = dao.deleteEmployeeById("00013"); System.out.println("삭제된 row 수 : "+cnt); System.out.println("-----전체 직원 부서 조회하기------"); List list = dao.selectAllEmployee(); for(Object obj:list){ EmployeeDTO dto = (EmployeeDTO)obj; System.out.println(dto.getEmployeeName()+" - "+dto.getDepartmentDTO().getDepartmentName()); } System.out.println("-----부서 조회하기-------"); list = dao.selectAllDepartment(); for(Object obj:list){ System.out.println(obj); } System.out.println("------봉급으로 조회-------"); HashMap map = new HashMap(); //map.put("start_salary", 2000000); map.put("end_salary", 10000000);
List list1 = dao.selectEmployeeBySalaryRange(map); for(Object obj:list1){ System.out.println(obj); } System.out.println("-----이름과 부서이름으로 조회--------"); EmployeeDTO edto1 = new EmployeeDTO(); // edto1.setEmployeeName("장"); edto1.setJobPosition("부"); List list2 = dao.selectEmployeeByNameOrPosition(edto1); for(Object obj:list2){ System.out.println(obj); }
System.out.println("-----iterate사용해서 여러명의 이름 중 있는 것만 조회하기------"); HashMap names = new HashMap(); String[] ns = {"한석규","길무성","김건모"}; names.put("names", ns); list = dao.selectEmployeeByNames(names); System.out.println(list.size()+"명 조회"); for(Object obj:list){ System.out.println(obj); } } }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="dept"> <select id="selectAllDepartment" resultClass="hr.dto.DepartmentDTO"> select department_id as departmentId, department_name as departmentName, location from department </select> </sqlMap>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="hr"> <typeAlias alias="empDTO" type="hr.dto.EmployeeDTO"/> <typeAlias alias="deptDTO" type="hr.dto.DepartmentDTO"/> <!-- insert --> <insert id="insertEmployee" parameterClass="empDTO"> <!-- <selectKey resultClass="int" keyProperty="employeeId"> select aaaa from dual </selectKey> --> insert into employee (employee_id,employee_name, email, job_position, salary, department_id) values(#employeeId#,#employeeName#,#email#,#jobPosition#,#salary#,#departmentDTO.departmentId#) </insert> <update id="updateEmployee" parameterClass="empDTO"> update employee set employee_name=#employeeName#, email=#email#, job_position=#jobPosition#, salary=#salary#, department_id=#departmentDTO.departmentId# where employee_id=#employeeId# </update> <delete id="deleteEmployeeById"> delete from employee where employee_id=#id# </delete> <resultMap class="empDTO" id="employeeResultMap"> <result property="employeeId" columnIndex="1"/><!--<result property="employeeId" column="employee_id"/>이렇게 줘도 되고 --> <result property="employeeName" columnIndex="2"/> <result property="email" columnIndex="3"/> <result property="jobPosition" columnIndex="4"/> <result property="salary" columnIndex="5"/> <result property="departmentDTO.departmentId" columnIndex="6"/> <result property="departmentDTO.departmentName" columnIndex="7"/> <result property="departmentDTO.location" columnIndex="8"/> </resultMap> <select id="selectAllEmployee" resultMap="employeeResultMap"> select emp.employee_id , emp.employee_name, emp.email, emp.job_position, emp.salary, dept.department_id, dept.department_name, dept.location from employee emp, department dept where emp.department_id = dept.department_id </select> <select id="selectEmployeeBySalaryRange" resultMap="employeeResultMap" parameterClass="hashmap"> select emp.employee_id , emp.employee_name, emp.email, emp.job_position, emp.salary, dept.department_id, dept.department_name, dept.location from employee emp, department dept where emp.department_id = dept.department_id <!-- and emp.salary > #start_salary# and emp.salary < #end_salary# -->
<!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <settings useStatementNamespaces="true"/><!-- namespace를 사용하겠다. true --> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/> <property name="JDBC.Username" value="scott"/> <property name="JDBC.Password" value="tiger"/> </dataSource> </transactionManager>
<!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) --> <!-- <sqlMap resource="config/member.xml"/> --> <sqlMap resource="hr/config/hr.xml"/> <sqlMap resource="hr/config/dept.xml"/> </sqlMapConfig>
<!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/> <property name="JDBC.Username" value="scott"/> <property name="JDBC.Password" value="tiger"/> </dataSource> </transactionManager>
public static void main(String[] args)throws Exception { DepartmentDTO deptDTO = new DepartmentDTO(); deptDTO.setDepartmentId("D0001"); EmployeeDTO empDTO = new EmployeeDTO("00013", "김건모", "abc@abc.com", "과장", 403000, deptDTO); EmployeeDAO dao = EmployeeDAO.getInstance();
// dao.insertEmployee(empDTO); empDTO.setSalary(5405050); empDTO.setJobPosition("부장"); int cnt = dao.updateEmployee(empDTO); System.out.println("변경된 row 수 : "+cnt); cnt = dao.deleteEmployeeById("00013"); System.out.println("삭제된 row 수 : "+cnt); System.out.println("-----전체 직원 부서 조회하기------"); List list = dao.selectAllEmployee(); for(Object obj:list){ EmployeeDTO dto = (EmployeeDTO)obj; System.out.println(dto.getEmployeeName()+" - "+dto.getDepartmentDTO().getDepartmentName()); } System.out.println("-----부서 조회하기-------"); list = dao.selectAllDepartment(); for(Object obj:list){ System.out.println(obj); } } }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="dept"> <select id="selectAllDepartment" resultClass="hr.dto.DepartmentDTO"> select department_id as departmentId, department_name as departmentName, location from department </select> </sqlMap>
<!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <settings useStatementNamespaces="true"/><!-- namespace를 사용하겠다. true --> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/> <property name="JDBC.Username" value="scott"/> <property name="JDBC.Password" value="tiger"/> </dataSource> </transactionManager>
<!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) --> <!-- <sqlMap resource="config/member.xml"/> --> <sqlMap resource="hr/config/hr.xml"/> <sqlMap resource="hr/config/dept.xml"/> </sqlMapConfig>