이안의 평일코딩

Spring 1일차 - DI(Dependency Injection 의존성 주입) 본문

Back-end/Spring

Spring 1일차 - DI(Dependency Injection 의존성 주입)

이안92 2020. 10. 20. 12:52
반응형

2020.10.20(화)

github.com/spring-projects/toolsuite-distribution/wiki/Spring-Tool-Suite-3

Properties-Project Facets-Java Version

 

<Spring>

*VO를 제외한 모든 클래스는 스프링에 관리 요청

사용자 정의 클래스를 모아서 관리 (생명주기)

=> 클래스 객체 생성 ~ 객체 소멸 ==> 관계도 설정 간단하다

  다른 클래스에 영향을 미치지 않는다

 결합성(의존성) 낮은 프로그램

    수정 => 다른 에러가 나는지 확인 

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

    메모리 할당 (스프링에서 한다) => 메모리를 낭비하지 않는다

 => 싱글턴

 XML : 클래스나 패키지 단위로 메모리 할당 요청

 Annotation : 클래스 찾기, 메소드 찾기

 Container : 클래스를 모아서 관리

 ==> ApplicationContext => application-context.xml

         ================== XML 파서

 ** DI : 주입 (setter, 생성자 매개변수에 값을 채운다)

 ** AOP : 반복을 제거 => 자동호출(콜백)

 ORM : Mapper(데이터베이스 연결)

 MVC : Web

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

 Spring 5 => 순수 자바만으로 코딩 (XML을 제외), kotlin (Annotation)

 

DL : 클래스를 찾을 때 사용

DI : 메모리 할당시에 필요한 데이터를 받는다

 

1. DI

aop - 자동호출

c - 생성사 매개변수 값

context - 패키지 단위로 메모리 할당

task - db백업 명령

tx - 트랜잭션, 일괄처리

util - properties 파일 읽음

beans - 클래스 메모리 할당

p - 값 주입할 때

websocket - 실시간

 

scope (기본은 singleton)

prototype => 매번 주소값을 다르게 줌, 메모리 따로 저장. 다른 값 저장 가능

singleton => 하나의 주소로 처리하는 방식. 계속 바꿔 나감.

 

 

OnLineSpringStudy2

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sist</groupId>
	<artifactId>music</artifactId>
	<name>OnLineSpringStudy2</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
	   <!-- Spring 5 -->
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.5.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<repositories>
	   <repository>
		    <id>mesir-repo</id>
		    <url>http://mesir.googlecode.com/svn/trunk/mavenrepo</url>
		</repository>
	</repositories>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
	    <!-- Jsoup -->
	    <dependency>
		    <groupId>org.jsoup</groupId>
		    <artifactId>jsoup</artifactId>
		    <version>1.13.1</version>
		</dependency>
		<!-- JSON -->
		<dependency>
		    <groupId>com.googlecode.json-simple</groupId>
		    <artifactId>json-simple</artifactId>
		    <version>1.1.1</version>
		</dependency>
		<!-- JAXB -->
		<dependency>
		    <groupId>javax.xml.bind</groupId>
		    <artifactId>jaxb-api</artifactId>
		    <version>2.3.1</version>
		</dependency>
		<!-- AspectJ -->
		<dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context-support</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>5.1.5.RELEASE</version>
		</dependency>
		<!-- lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.8</version>
		    <scope>provided</scope>
		</dependency>
      <!-- websocket -->
      <dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-websocket</artifactId>
		    <version>5.1.5.RELEASE</version>
		</dependency>
      
      <!-- <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-expression</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency> -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-instrument</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aspects</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <!-- <dependency>
         <groupId>com.oracle</groupId>
         <artifactId>ojdbc14</artifactId>
         <version>10.2.0.4.0</version>
      </dependency> -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jms</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-orm</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-oxm</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-test</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency>
      <!-- <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc-portlet</artifactId>
         <version>5.1.5.RELEASE</version>
      </dependency> -->
      
      <dependency>
         <groupId>taglibs</groupId>
         <artifactId>standard</artifactId>
         <version>1.1.2</version>
      </dependency>

      <dependency>
         <groupId>org.nuiton.thirdparty</groupId>
         <artifactId>Rserve</artifactId>
         <version>1.7-3</version>
      </dependency>
      <dependency>
         <groupId>org.nuiton.thirdparty</groupId>
         <artifactId>REngine</artifactId>
         <version>1.7-3</version>
      </dependency>
      <!-- 
         @Select("<script>SELECT~~ <if test="">")
       -->
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis</artifactId>
         <version>3.2.8</version>
      </dependency>
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis-spring</artifactId>
         <version>1.2.0</version>
      </dependency>
      <dependency>
         <groupId>org.mongodb</groupId>
         <artifactId>mongo-java-driver</artifactId>
         <version>2.13.0-rc1</version>
      </dependency>
      <dependency>
         <groupId>org.nuiton.thirdparty</groupId>
         <artifactId>JRI</artifactId>
         <version>0.9-6</version>
      </dependency>
      <dependency>
         <groupId>com.github.lucarosellini.rJava</groupId>
         <artifactId>JRIEngine</artifactId>
         <version>0.9-7</version>
      </dependency>
      <dependency>
         <groupId>aopalliance</groupId>
         <artifactId>aopalliance</artifactId>
         <version>1.0</version>
      </dependency>
      <dependency>
         <groupId>asm</groupId>
         <artifactId>asm</artifactId>
         <version>3.3.1</version>
      </dependency>
      <dependency>
         <groupId>c3p0</groupId>
         <artifactId>c3p0</artifactId>
         <version>0.9.1.2</version>
      </dependency>
      <dependency>
         <groupId>cglib</groupId>
         <artifactId>cglib</artifactId>
         <version>3.1</version>
      </dependency>
      <dependency>
         <groupId>cglib</groupId>
         <artifactId>cglib-nodep</artifactId>
         <version>3.1</version>
      </dependency>
      <dependency>
         <groupId>commons-collections</groupId>
         <artifactId>commons-collections</artifactId>
         <version>3.2.1</version>
      </dependency>
      <dependency>
         <groupId>commons-dbcp</groupId>
         <artifactId>commons-dbcp</artifactId>
         <version>1.4</version>
      </dependency>
      <dependency>
         <groupId>commons-fileupload</groupId>
         <artifactId>commons-fileupload</artifactId>
         <version>1.3.1</version>
      </dependency>
      <dependency>
         <groupId>commons-io</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.4</version>
      </dependency>
      <dependency>
         <groupId>commons-logging</groupId>
         <artifactId>commons-logging</artifactId>
         <version>1.2</version>
      </dependency>
      <dependency>
         <groupId>commons-pool</groupId>
         <artifactId>commons-pool</artifactId>
         <version>1.6</version>
      </dependency>
      <dependency>
         <groupId>org.javassist</groupId>
         <artifactId>javassist</artifactId>
         <version>3.18.2-GA</version>
      </dependency>
	  
      <dependency>
         <groupId>org.nuiton.thirdparty</groupId>
         <artifactId>Rserve</artifactId>
         <version>1.7-3</version>
      </dependency>
      <dependency>
         <groupId>org.nuiton.thirdparty</groupId>
         <artifactId>REngine</artifactId>
         <version>1.7-3</version>
      </dependency>
      <dependency>
			<groupId>org.twitter4j</groupId>
			<artifactId>twitter4j-core</artifactId>
			<version>4.0.2</version>
		</dependency>
        <dependency>
			<groupId>org.twitter4j</groupId>
			<artifactId>twitter4j-stream</artifactId>
			<version>4.0.2</version>
		</dependency>
        <dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
       <!--  <dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.4.0</version>
		</dependency> -->
        
		<!-- End -->	
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		 <!-- AOP -->
      <dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.5</version>
		</dependency>
      <!-- AOP -->
      <dependency>
         <groupId>aopalliance</groupId>
         <artifactId>aopalliance</artifactId>
         <version>1.0</version>
      </dependency>
      <!-- AOP -->
      <dependency>
		<groupId>asm</groupId>
		<artifactId>asm</artifactId>
		<version>3.1</version>
	</dependency>
		<!-- tiles  -->
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-core</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-jsp</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-api</artifactId>
			<version>2.2.2</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-servlet</artifactId>
			<version>2.2.2</version>
		</dependency>
		
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.2</version>
		</dependency>
		
		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
			<version>2.1</version>
		</dependency>
		
		<dependency>
			<groupId>org.antlr</groupId>
			<artifactId>antlr-runtime</artifactId>
			<version>3.5.2</version>
		</dependency>
		<!-- XML -->
		<dependency>
			<groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-core</artifactId>
			<version>2.2.11</version>
		</dependency>
		<dependency>
			<groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-impl</artifactId>
			<version>2.2.11</version>
		</dependency>

		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.2.11</version>
		</dependency>
		
		<!-- 
		   jaxb-core
		   jaxb-impl
		   jaxb-api
		   
		   json-simple
		   commons-lang
		   ezmorph
		 -->
		<!-- JSON -->
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <!-- Spring 5 -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
	

 

src/main/java

com.sist.music

MainController.java

package com.sist.music;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {
	@RequestMapping("main/main.do")
	public String main_main(HttpServletRequest request) {
		request.setAttribute("msg", "Hello Spring");
		return "main/main";
	}
}

 

src/main/webapp/main

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<center>
		<h1>${msg }</h1>
	</center>
</body>
</html>

 

src/main/webapp/WEB-INF

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: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">
	<context:component-scan base-package="com.sist.*"/>
	<!-- 
		@RequestMapping()
		public String aaa(){
			return "../main/main.jsp";
		}
	 -->
	 <!-- 
	 		class InternalResourceViewResolver{
	 			private String prefix; // 경로명
	 			private String suffix; // 확장자
	 		}
	  -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/"
		p:suffix=".jsp"
	/>
</beans>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/app.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

 

 

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

OnLineSpringDIStudy1

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: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="aa" class="com.sist.music.Abc">
		 Class cls=Class.forName("com.sist.music.Abc");
		 Object obj=cls.newInstance();
		 
		 Map map = new HashMap();
		 map.put("aa",obj);
		 
	 -->
	 <!-- 
	 	Sawon sa=new Sawon();
	 	sa.setName("이안");
	 	sa.setSex("남자");
	 	sa.setAge(20);
	  -->
	<bean id="sa" class="com.sist.di.Sawon" scope="prototype">
	 <!-- 1. value 별개로 -->
	 <property name="name">
	  <value>이안</value>
	 </property>
	 
	 <!-- 2. value값 함께 -->
	 <property name="sex" value="남자"/>
	 
	 <property name="age">
	  <value>20</value>
	 </property>
	</bean>
	<!-- 3. p클론 이용 -->
	<bean id="sal" class="com.sist.di.Sawon"
	 p:name="심청이"
	 p:sex="여자"
	 p:age="20"
	/>
	
</beans>

app1.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">
	<!-- Member클래스 생성 => 값 주입 -->
	<bean id="mem" class="com.sist.di3.Member"
		p:no="1"
		p:name="이순신"
		p:sex="남자"
		p:addr="서울"
		p:tel="010-0000-0000"
	/>
	<!-- MemberList 클래스 생성 => member객체를 전송 -->
	<bean id="ml" class="com.sist.di3.MemberList"
		p:mem-ref="mem"
	/>
</beans>

 

src/main/java

com.sist.di

MainClass.java

package com.sist.di;

public class MainClass {

	public static void main(String[] args) {
		Sawon s=new Sawon();
		s.setName("홍길동");
		s.setSex("남자");
		s.setAge(20);
		// DI(의존성 주입)
		s.init();
		///////////////////////////
		s.print(); // 프로그래머가 호출
	}
}

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) {
		// XML파싱
		ApplicationContext app=new ClassPathXmlApplicationContext("app.xml");
		Sawon sa=(Sawon)app.getBean("sa");
		System.out.println("sa="+sa);
		sa.init();
		sa.print();
		
		Sawon sa1=(Sawon)app.getBean("sa");
		System.out.println("sa1="+sa1);
		sa.init();
		sa.print();
	}

}

Sawon.java

package com.sist.di;
/*
 * 	메모리 할당
 *  setXxx()에 값 채운다
 *  init()
 *  print()
 *  
 */
public class Sawon {
	private String name;
	private String sex;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void init() {
		System.out.println("===== 사원 정보 =====");
	}
	public void print() {
		System.out.println("이름:"+name);
		System.out.println("성별:"+sex);
		System.out.println("나이:"+age);
	}
}

 

com.sist.di2

ApplicationContext.java

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

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/*
 * 	class A{
 * 		B b;
 * 		public void setB(B b){
 * 			this.b=b;
 * 		}
 * 	}
 * 
 *  <bean id="a" class="A">
 *   <property name="b" ref="b">
 *  </bean>
 *  <bean id="b" class="B">
 */
import java.io.*;

public class ApplicationContext {
	private Map map = new HashMap();
	public ApplicationContext(String path) {
		try {
			SAXParserFactory spf=SAXParserFactory.newInstance();
			SAXParser sp=spf.newSAXParser();
			XMLParser xp=new XMLParser();
			sp.parse(new File(path), xp);
			map=xp.map;
		}catch(Exception ex) {}
	}
	// DL (lookup) => 이름(key)를 가지고 클래스 객체 주소를 찾아주는 역할
	public Object getBean(String key) {
		return map.get(key);
	}
}

MainClass.java

package com.sist.di2;

import com.sist.di.Sawon;

public class MainClass {

	public static void main(String[] args) {
		ApplicationContext app = new ApplicationContext("/Users/yongpro/Desktop/JAVA1/springDev/OnLineSpringDIStudy1/src/main/java/com/sist/di2/app.xml");
		Sawon sa = (Sawon)app.getBean("sa");
		System.out.println("sa="+sa);
		sa.init();
		sa.print();
		
		Sawon sa1 = (Sawon)app.getBean("sa");
		System.out.println("sa1="+sa1);
		sa.init();
		sa.print();
	}

}

XMLParser.java

package com.sist.di2;

import org.aspectj.apache.bcel.classfile.Method;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.*;


public class XMLParser extends DefaultHandler {
	Map map=new HashMap();
	Object obj;
	Class clsName;
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		try {
			if(qName.equals("bean")) {
				String id=attributes.getValue("id");
				String cls=attributes.getValue("class");
				clsName=Class.forName(cls);
				obj=clsName.newInstance();
				map.put(id, obj);
			}
			if(qName.equals("property")) {
				String name = attributes.getValue("name");
				String value = attributes.getValue("value");
				java.lang.reflect.Method[] methods=clsName.getDeclaredMethods();
				for(java.lang.reflect.Method m:methods) {
					if(m.getName().equalsIgnoreCase("set"+name)) {
						if(name.equals("age")) {
							m.invoke(obj, Integer.parseInt(value));
						}
						else {
							m.invoke(obj, value);
						}
					}
				}
			}
		}catch(Exception ex) {}
	}
	
}

app.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
 <bean id="sa" class="com.sist.di.Sawon">
  <property name="name" value="홍길동"/>
  <property name="age" value="20"/>
  <property name="sex" value="남자"/>
 </bean>
</beans>

 

com.sist.di3

MainClass.java

package com.sist.di3;

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

public class MainClass {

	public static void main(String[] args) {
		ApplicationContext app = new ClassPathXmlApplicationContext("app1.xml");
		// ClassPath : /Users/yongpro/Desktop/JAVA1/springDev/OnLineSpringDIStudy1/src/main/java
		MemberList ml=(MemberList)app.getBean("ml"); // Object형변환
		// MemberList ml=app.getBean("ml",MemberList.class);
		// 제네릭스 : 데이터 통합 List<String>
		/*
		 * T => TYPE => 임시 변수 A<String>
		 * class A<T>{
		 * T t;
		 *  public T getT(){
		 * 	 return T;
		 *  }
		 *  public void setT(T t){
		 *   this.t=t;
		 *  }
		 * }
		 */
		ml.print();
	}
}

Member.java

package com.sist.di3;

public class Member {
	private int no;
	private String name;
	private String sex;
	private String addr;
	private String tel;
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	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;
	}
	
}

MemberList.java

package com.sist.di3;
/*
 * 	== 결합성(의존성) 높은 프로그램
 *  == 결합성(의존성) 낮은 프로그램 (스프링은 낮은 프로그램을 사용한다)
 *     ==========
 *     영향력 => 다른 클래스
 *     응집성 => 관련된 메소드를 잘 묶어서 사용
 * 값 대입
 *   = 일반 변수값
 *   = 클래스 주소값 (ref) ref="bean태그의 id명을 부여"
 *   Member mem=new Member();
 *   MemberList ml=new MemberList();
 *   ml.setMem(mem)
 */
public class MemberList {
	private Member mem;

	public Member getMem() {
		return mem;
	}

	public void setMem(Member mem) {
		this.mem = mem;
	}
	
	public void print() {
		System.out.println("회원번호:"+mem.getNo());
		System.out.println("이름:"+mem.getName());
		System.out.println("성별:"+mem.getSex());
		System.out.println("주소:"+mem.getAddr());
		System.out.println("전화:"+mem.getTel());
	}
}

 

 

반응형

'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 2일차 - XML, Configuration  (0) 2020.10.21
Comments