이안의 평일코딩

Spring 2일차 - XML, Configuration 본문

Back-end/Spring

Spring 2일차 - XML, Configuration

이안92 2020. 10. 21. 10:55
반응형

2020.10.21(수)

 

ORM(MyBatis)

 

Spring은 Container다

Container : 관리(조립) => 클래스를 모아서 관리

스프링에서 지원 (page 49)

============

   BeanFactory ==> CORE(DI)

           |

   ApplicationContext         AnnotationConfigApplicationContext

           |        DI, AOP                                     |

WebApplicationContext    WebAnnotationConfigApplicationContext

                    DI, AOP, MVC

 

=> XML, Annotation에 등록된 클래스를 읽어서 관리

 

Component : 클래스 한개

컴퓨터 : CPU(메인보드), 메모리, 하드...

 

 

OnLineSpringDIStudy2

pom.xml

 

src/main/java

app.xml

<?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:c="http://www.springframework.org/schema/c"
	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"> 디폴트 생성자 호출
		class A{
		   ===> public A(){
		}
		class A{
		             매개변수
			public A(int a){} // 생성자 있으면 디폴트 안생김
		}
		A a = new A(); (X)
		A a = new A(10); (O)
	 -->
	<bean id="mem" class="com.sist.di.Member">
	 <constructor-arg value="홍길동" index="0"/>
	 <!--  <constructor-arg value="010-1111-1111" index="2"/> -->
	 <constructor-arg value="서울" index="1"/>
	 <constructor-arg>
	 	<value>010-1111-1111</value>
	 </constructor-arg>
	</bean>
	<bean id="mem2" class="com.sist.di.Member"
	 c:name="심청이"
	 c:addr="경기"
	 c:tel="010-2222-2222"
	/>
	<bean id="mem3" class="com.sist.di.Member"
	 c:_0="박문수"
	 c:_1="인천"
	 c:_2="010-3333-3333"
	/>
</beans>

 

com.sist.di

ApplicationConfig.java

package com.sist.di;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// XML 대체
@Configuration
public class ApplicationConfig {
	// 클래스
	@Bean("sa")
	//@Scope("") 생략하면 Singleton
	/* 
	 *  <bean id="sa" class="Sawon"
	 * 	 p:name="홍길동"
	 * 	 p:addr="서울"
	 *   p:tel="010-1111-1111"
	 *  />
	 */
	public Sawon sawonInfo() {
		Sawon sa=new Sawon();
		sa.setName("홍길동");
		sa.setAddr("서울");
		sa.setTel("010-1111-1111");
		return sa;
	}
	// 생성
	@PostConstruct
	// <bean id="sa" class="Sawon" init=method="init destroy-method="destroy">
	/*
	 * 	메소드 호출
	 *     객체생성시 : init-method (@PostConstruct)
	 *     			 ============= DB (드라이버 등록)
	 *     객체소멸시 : destroy-method (@PreDestroy)
	 *     			 ============= DB (disConnection)
	 *     
	 *  DI
	 *    = setter DI
	 *    = method DI (init-method, destroy-method)
	 *    = constructor DI 생성자 매개변수 값 주입
	 *    = 자동 주입
	 */
	public void init() {
		System.out.println("===사원정보===");
	}
	// 소멸
	@PreDestroy
	public void destroy() {
		System.out.println("============");
	}
}

 

MainClass.java

package com.sist.di;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		// 등록된 클래스를 관리 => 클래스가 필요시마다 app를 통해서 객체주소 얻어온다
		// 객체 생성 ~ 소멸
		// 보안 (소스가 노출)
		AnnotationConfigApplicationContext app =
				new AnnotationConfigApplicationContext(ApplicationConfig.class);
		Sawon s1 = app.getBean("sa", Sawon.class); // 제네릭스
		// (Sawon)app.getBean("sa") 오브젝트 리턴 형변환시켜도됨
		System.out.println("이름:"+s1.getName());
		System.out.println("주소:"+s1.getAddr());
		System.out.println("전화:"+s1.getTel());
		
		app.close();
	}

}

 

MainClass2.java

package com.sist.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass2 {

	public static void main(String[] args) {
		ApplicationContext app=new ClassPathXmlApplicationContext("app.xml");
		Member m1=(Member)app.getBean("mem");
		m1.print();
		Member m2=app.getBean("mem2",Member.class);
		m2.print();
		Member m3=(Member)app.getBean("mem3");
		m3.print();
	}
	
}

 

Member.java

package com.sist.di;
// 생성자 DI ==> 객체 생성시에 생성자 매개변수에 값을 채워라
/*
 * 	XML, Annotation => 스프링에 요청
 *  ==> 프로그램
 *      개발자 전체 처리 (소프트웨어 전체)
 *      필요시마다 스프링에 요청 => 값을 얻어온다 (소프트웨어를 제어하는 제어권 => 스프링)
 *        => 제어의 역전 (IoC) => 마틴 파울러
 *      => 소프트웨어 기반으로 프로그램을 제작 (로드 존슨) => 스프링
 *      스프링 => IoC Container (경량 컨테이너)
 * 
 */
public class Member {
	private String name;
	private String addr;
	private String tel;
	public Member(String name, String addr, String tel) {
		this.name = name;
		this.addr = addr;
		this.tel = tel;
	}
	public void print() {
		System.out.println("이름:"+name);
		System.out.println("주소:"+addr);
		System.out.println("전화:"+tel);
	}
}

 

Sawon.java

package com.sist.di;
/*
 * 	Container : 관리(조립) => 클래스 모아서 관리
 *  Component : 클래스 한개
 *  	  메인보드
 *  컴퓨터 : CPU, 메모리, 하드...
 */
public class Sawon {
	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;
	}
	
}

 

src/main/java

app2.xml

<?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:c="http://www.springframework.org/schema/c"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<context:component-scan base-package="com.sist.di2"/>
	<!-- 
		DL : 클래스 찾을 때
		@Component : 일반 클래스
		@Repository : DAO
		@Service : DAO 여러개 연결 (조인)
		@Controller : Model
		@RestController : Model (restful) => JSON
		@ControllerAdvice : AOP
		@Configuration : 환경설정 (클래스 등록)
	 -->
	 <!-- 
	 	 DI : 값을 넣어줄 때
	 	 @Required
 		 @Autowired
 		 @PostConstruct
 		 @PreDestroy
 		 @Resource
 		 @PersistenceContext
 		 @PersistenceUnit
	  -->
	<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"
	/>
	<!-- MyBatis 연결 -->
	<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="ds"
	/>
	<!-- EmpMapper 구현 -->
	<bean id="mapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
		p:sqlSessionFactory-ref="ssf"
		p:mapperInterface="com.sist.di2.EmpMapper"
	/>
</beans>

 

com.sist.di2

EmpVO.java

package com.sist.di2;

public class EmpVO {
	private int empno;
	private String ename;
	private String job;
	private int sal;
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public int getSal() {
		return sal;
	}
	public void setSal(int sal) {
		this.sal = sal;
	}
}

 

EmpMapper.java

package com.sist.di2;
import java.util.*;

import org.apache.ibatis.annotations.Select;
public interface EmpMapper {
		@Select("SELECT empno, ename, job, sal FROM emp")
		public List<EmpVO> empAllData();
}

 

EmpDAO.java

package com.sist.di2;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Service
// empDAO 클래스 맨앞자만 소문자로 바뀜
public class EmpDAO {
	@Autowired
	private EmpMapper mapper;
	public List<EmpVO> empAllData(){
		return mapper.empAllData();
	}
}

 

MainClass.java

package com.sist.di2;
import java.util.*;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
	public static void main(String[] args) {
		ApplicationContext app=new ClassPathXmlApplicationContext("app2.xml");
		EmpDAO dao=(EmpDAO)app.getBean("empDAO");
		List<EmpVO> list=dao.empAllData();
		for(EmpVO vo:list) {
			System.out.println(vo.getEmpno()+" "
					+vo.getEname()+" "
					+vo.getJob()+" "
					+vo.getSal());
		}
	}
}

 

 

com.sist.di3

ApplicationConfig.java (XML을 대신 사용)

package com.sist.di3;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// 메모리 할당
@Configuration
public class ApplicationConfig {
	// <bean> XML => 대처하는 프로그램 (어노테이션)
	// 싱글턴 (같은 메모리가 들어옴) 또는 @Scope("prototype")
	@Bean("mem")
	public Member memberInfo() {
		Member m=new Member("이순신", "강원", "010-1111-1111");
		return m;
	}
}

 

MainClass.java

package com.sist.di3;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// map.put("mem",new Member())
public class MainClass {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext app=
				new AnnotationConfigApplicationContext(ApplicationConfig.class);
		Member m=app.getBean("mem",Member.class);
		m.print();
	}
}

 

Member.java

package com.sist.di3;

public class Member {
	private String name, addr, tel;

	public Member(String name, String addr, String tel) {
		this.name = name;
		this.addr = addr;
		this.tel = tel;
	}
	public void print() {
		System.out.println("이름:"+name);
		System.out.println("주소:"+addr);
		System.out.println("전화:"+tel);
	}
}

 

 

=================================================================

OnLineSpringDIStudy3

 

* XML

src.main.java

app.xml

<?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="s1" class="com.sist.di.Student"
		p:name="홍길동"
		p:kor="80"
		p:eng="85"
		p:math="90"
	/>
	<bean id="s2" class="com.sist.di.Student"
		p:name="심청이"
		p:kor="90"
		p:eng="75"
		p:math="80"
	/>
	<bean id="s3" class="com.sist.di.Student"
		p:name="박문수"
		p:kor="95"
		p:eng="80"
		p:math="100"
	/>
	<!-- 알고 있어야 한다 : Restful => 한글 처리 -->
	<bean id="school" class="com.sist.di.School">
		<property name="list">
			<list>
				<ref bean="s1"/><!-- list.add(s1) -->
				<ref bean="s2"/>
				<ref bean="s3"/>
			</list>
		</property>
	</bean>
</beans>

 

com.sist.di

Student.java

package com.sist.di;
/*
 * <bean id="s" class="Student" init-method="init" destroy-method="destroy"
 * 	 p:name="홍길동"  => setterDI
 *   p:kor=90
 *   p:eng=70
 *   p:math=80
 * >
 * 
 *  동작
 *  1) Class.forName("Student") => 메모리 할당
 *  2) setXxx()에 값을 채워준다
 *  3) init-method=> 호출
 *  ===========================================
 *  4) 프로그래머 선택
 *  ===========================================
 *  5) destroy-method => 호출
 *  ===========================================
 */
public class Student {
	private String name;
	private int kor;
	private int eng;
	private int math;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMath() {
		return math;
	}
	public void setMath(int math) {
		this.math = math;
	}
	
}

 

School.java

package com.sist.di;
import java.util.*;
public class School {
	private List<Student> list=
			new ArrayList<Student>();

	public void setList(List<Student> list) {
		this.list = list;
	}
	public void print() {
		for(Student s:list) {
			System.out.println(s.getName()+" "
					+s.getKor()+" "
					+s.getEng()+" "
					+s.getMath());
		}
	}
}

 

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) {
		ApplicationContext app=new ClassPathXmlApplicationContext("app.xml");
		School ss=(School)app.getBean("school");
		ss.print();
	}

}

 

반응형

'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 3일차 - Container  (0) 2020.10.22
Spring 1일차 - DI(Dependency Injection 의존성 주입)  (0) 2020.10.20
Comments