이안의 평일코딩

Spring 6일차 - ComponentScan 본문

Back-end/Spring

Spring 6일차 - ComponentScan

이안92 2020. 10. 31. 14:17
반응형

2020.10.27(화)

메모리 할당

@Component : 일반 클래스 (Sawon, MainClass...)

@Repository : DAO

@Controller : Model

@Service : Manager, DAO+DAO

@RestController : 파일 전송없이 일반 문자열 전송 (Ajax, React ...)

======>  Spring

               =======

               1. DI, Container개념

               2. AOP VS OOP

               3. DAO VS Service

 

주입 (Inject) (메모리에 저장된 객체 주소를 가지고 올 때 사용), 일반 변수는 사용할 수 없다

@Autowired : 스프링에서 저장된 클래스 중에 맞는 주소 찾아서 자동 주입

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

@Resource

@Qualifier

@Inject

=================== 특정객체를 지정할 경우

@ComponentScan(basePackages={"com.sist.di"})

 


OnLineSpringDIStudy8

src/main/java

app.xml (beans, c, 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:c="http://www.springframework.org/schema/c"
	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.di5.Sawon"
	  c:name="박문수"
	  c:dept="개발부"
	  p:name="심청이"
	  p:dept="영업부"
	  scope="prototype"
	/>
</beans>

src/main/java

com.sist.di

AppConfig.java

package com.sist.di;

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

//app.xml
@Configuration
@ComponentScan(basePackages = {"com.sist.di"})
public class AppConfig {
	
}

 

Member.java

package com.sist.di;

import org.springframework.stereotype.Component;

@Component("mem")
public class Member {
	private String name="홍길동";
	private String addr="서울";
	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;
	}
	
}

 

Sawon.java

package com.sist.di;

import org.springframework.stereotype.Component;

@Component("sa")
public class Sawon {
	private String name="심청이";
	private String sex="여자";
	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;
	}
	
}

 

MainClass.java

package com.sist.di;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

@Component("mc")
public class MainClass {
	@Autowired
	private Sawon sa;
	@Autowired
	private Member mem;
	public static void main(String[] args) {
		AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(AppConfig.class);
		// 132page
		MainClass mc=(MainClass)app.getBean("mc");
		System.out.println("===사원 정보===");
		System.out.println("이름:"+mc.sa.getName());
		System.out.println("성별:"+mc.sa.getSex());
		System.out.println("===회원 정보===");
		System.out.println("이름:"+mc.mem.getName());
		System.out.println("주소:"+mc.mem.getAddr());
	}

}

 

/*
 * 1. 클래스 => 메모리 할당 => 저장 공간 (Container)
 * 	  ApplicationContext => Map
 * 
 * 2. 클래스 찾기 : DL
 * 3. 생성과 동시에 필요한 데이터가 있는 경우
 * 	  ======================= 처리 ==> DI setter(p:), constructor(c:)
 * 	
 * 4. 활용 : 프로그래머
 * 5. 소멸 : 메모리 해제
 * 
 *    @Component
 *    class Sawon
 *    
 *    @Component("mem")
 *    class Member
 * 	  ====================
 *      key      value
 *    ====================
 *     sawon     new Sawon()
 *    ====================
 *     mem       new Member() => getBean("mem") ==> Member m = app.getBean("mem"); ~> new Member()									
 *    ====================
 * 	  AnnotationConfigApplicationContext
 *    = MVC = WebAppliationContext
 */

com.sist.di2

Sawon.java

package com.sist.di2;

import org.springframework.stereotype.Component;

@Component("sa")
public class Sawon {
	private String name="심청이";
	private String dept="개발부";
	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;
	}
	
}

 

com.sist.di3

Member.java

package com.sist.di3;

import org.springframework.stereotype.Component;

@Component("mem")
public class Member {
	private String name="홍길동";
	private String tel="010-1111-1111";
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	
}

 

com.sist.di4

AppConfig.java

package com.sist.di4;

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

@Configuration
@ComponentScan(basePackages = {"com.sist.di2","com.sist.di3","com.sist.di4"})

public class AppConfig {

}

 

MainClass.java

package com.sist.di4;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import com.sist.di2.*;
import com.sist.di3.*;

@Component
public class MainClass {
	@Resource(name="sa")
	private Sawon sa;
	@Resource(name="member")
	private Member mem;
	public static void main(String[] args) {
		// 초기화
		// MainClass mc=new MainClass();
		AnnotationConfigApplicationContext app=new AnnotationConfigApplicationContext(AppConfig.class);
		MainClass mc=(MainClass)app.getBean("mainClass");
		System.out.println("===사원 정보===");
		System.out.println(mc.sa.getName());
		System.out.println(mc.sa.getDept());
		System.out.println("===회원 정보===");
		System.out.println(mc.mem.getName());
		System.out.println(mc.mem.getTel());
	}
}

 

com.sist.di5

Sawon.java

package com.sist.di5;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/*
 * 스프링에서 생명주기 관련 인터페이스
 * InitializingBean : 초기화
 * DisposableBean: 소멸
 * 
 * 순서 (초기화)
 * 1. 생성자 => 멤버변수에 값을 채운다 => 메모리 할당
 * 2. afterPropertiesSet() => setName, setDept
 * ============================================
 * 3. print() => 프로그래머 활용
 * ============================================
 * 4. close() => destroy()
 */
public class Sawon implements InitializingBean, DisposableBean{
	private String name;
	private String dept;
	public Sawon(String name,String dept) {
		System.out.println("생성자 호출(Sawon(String name,String dept))");
		this.name=name;
		this.dept=dept;
	}
	public void print() {
		System.out.println("프로그래머가 활용:print()");
		System.out.println("이름:"+name);
		System.out.println("부서:"+dept);
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		System.out.println("setterDI(setName())");
		this.name = name;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		System.out.println("setterDI(setDept())");
		this.dept = dept;
	}
	@Override
	public void destroy() throws Exception {
		System.out.println("객체 소멸:destroy()");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("setter DI 시작:afterPropertiesSet()");
	}

}

 

MainClass.java

package com.sist.di5;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {
	/*
	 * GenericXmlApplicationContext => XML파싱
	 * GenericApplicationContext => XML파싱기능이 없다 (어노테이션 용도)
	 */
	public static void main(String[] args) {
		GenericXmlApplicationContext app = new GenericXmlApplicationContext("app.xml");
		//ApplicationContext app=new ClassPathXmlApplicationContext("app.xml");
		Sawon sa1=(Sawon)app.getBean("sa");
		// 사용범위(Scope) => 싱글턴, ProtoType
		Sawon sa2=(Sawon)app.getBean("sa");
		System.out.println("sa1:"+sa1);
		System.out.println("sa2:"+sa2);
		sa1.print();
		app.close();
	}
}

 


OnLineSpringDIStudy9

src/main/java

app.xml (aop, 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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
	<context:component-scan base-package="com.sist.*"/>
	<aop:aspectj-autoproxy/>
</beans>

 

src/main/java

com.sist.aop

MainClass.java

package com.sist.aop;

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");
		MyDAO dao=(MyDAO)app.getBean("myDAO");
//		dao.select("홍길동");
//		dao.insert();
//		dao.update();
		dao.db_insert();
		dao.db_select("");
		dao.db_update();
		dao.print();
	}
}

 

MyAspect.java

package com.sist.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/*
 * public void select(){
 * 	try{
 * 		%%%%%%%% ==> Before
 * 		insert();  Around ==> JoinPoint PointCut
 *  }catch(Exception ex){
 *  	%%%%%%%% ==> After-Throwing
 *  }finally{
 *  	%%%%%%%% ==> After
 *  }
 *  return; %%%%%%% ==> After-Returning
 * }
 */
// 공통 모듈
@Aspect
@Component
public class MyAspect {
	@Autowired
	private MyDAO dao;
	@Before("execution(* com.sist.aop.MyDAO.db_*(..))")
	// * 리턴형 (관계없이 처리) db_*() => 매개변수가 없는 상태
	// db_*(int) db_*(String,String) db_*(..) 매개변수존재(O), 존재(X)
	/*
	 * 	1. Before
	 *  2. After
	 *  3. After-Throwing
	 *  4. After-Returning
	 *  5. Around
	 *  =================== 호출 위치 (JoinPoint)
	 *  적용되는 메소드 설정 ==> PointCut
	 *  ======================================= Advice 여러개 ==> Aspect
	 *  
	 *  ==> Proxy 패턴
	 *      =========
	 *        => 대신 호출 (대체자)
	 *  class A{
	 *  	public void display(){
	 *  		System.out.println("display()");
	 *  	}
	 *  }
	 *  //// 라이브러리 제작
	 *  class Proxy{
	 *  	public void display(A a){
	 *  		System.out.println("Before");
	 *  		a.display();
	 * 		 	System.out.println("After");
	 *  	}
	 *  }
	 *  A a = new A();
	 *  a.display(); ==> X
	 *  Proxy p = new Proxy();
	 *  p.display(a); ==> O
	 */
	public void before() {
		dao.getConnection();
	}
	@After("execution(* com.sist.aop.MyDAO.db_*(..))")
	public void after() {
		dao.disConnection();
	}
}

 

MyDAO.java

package com.sist.aop;

import org.springframework.stereotype.Repository;

/*
 * AOP는 사용자 정의(X) ==> Transaction, 보안
 * @Transactional
 * public void allData(){
 * 		insert(); // 입고
 * 		insert(); // 재고
 * }
 * 
 * public void allData(){
 * 	try{
 * 		getConnection();
 * 		conn.setAutoCommit(false);
 * 		insert(); // 입고
 * 		insert(); // 재고
 * 		conn.commit();
 * 		update();
 *  }catch(Exception ex){
 *  	conn.rollback();
 *  }finally{
 *  	conn.setAutoCommit(true);
 *  	disConnection();
 *  }
 */
@Repository
public class MyDAO {
	public void getConnection() {
		System.out.println("오라클 연결...");
	}
	public void disConnection() {
		System.out.println("오라클 연결 종료...");
	}
	public void db_select(String name) {
		//getConnection();
		System.out.println("SELECT 문장 실행...");
		//disConnection();
	}
	public void db_insert() {
		//getConnection();
		System.out.println("INSERT 문장 실행...");
		//disConnection();
	}
	public void db_update() {
		//getConnection();
		System.out.println("UPDATE 문장 실행...");
		//disConnection();
	}
	public void print() {
		System.out.println("완료");
	}
}

 


OnLineSpringDISutdy10

src/main/webapp/WEB-INF/

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/config/application-context.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	<filter>
	    <filter-name>encodingFilter</filter-name>
	    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	    <init-param>
	        <param-name>encoding</param-name>
	        <param-value>UTF-8</param-value>
	    </init-param>
	    <init-param>
	        <param-name>forceEncoding</param-name>
	        <param-value>true</param-value>
	    </init-param>
	</filter>

	<filter-mapping>
	    <filter-name>encodingFilter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

src/main/java

com.sist.aop

BoardController.java

package com.sist.aop;

import org.json.simple.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BoardController {
	@RequestMapping("board/update.do")
	public String board_update() {
		JSONObject obj=new JSONObject();
		obj.put("name", "홍길동");
		obj.put("sex", "남자");
		return obj.toJSONString();
	}
}

 

BoardService.java

package com.sist.aop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// BI
@Service
public class BoardService {
	@Autowired
	private MyDAO mdao;
	
	@Autowired
	private YouDAO ydao;
}

 

MainController.java

package com.sist.aop;

import javax.servlet.http.HttpServletRequest;

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

// 메모리 할당
@Controller
public class MainController {
	@RequestMapping("main/main.do")
	public String main_main(MemberVO vo, Model model) {
		model.addAttribute("vo", vo);
		return "main/main";
	}
}

 

MemberVO.java

package com.sist.aop;

public class MemberVO {
	private String name;
	private String sex;
	private String addr;
	private String tel;
	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;
	}
	
}

 

MyDAO.java

package com.sist.aop;

import org.springframework.stereotype.Repository;

@Repository
public class MyDAO {
	public void replyAllData() {
		System.out.println("replyAllData() Call..");
	}
}

 

YouDAO.java

package com.sist.aop;

import org.springframework.stereotype.Repository;

@Repository
public class YouDAO {
	public void boardAllData() {
		System.out.println("boardAllData() Call...");
	}
}
반응형

'Back-end > Spring' 카테고리의 다른 글

Spring 8일차 - MyBatis 연동  (0) 2020.11.03
Spring 7일차 - XML MVC구조  (0) 2020.11.02
Spring 5일차 - Repository  (0) 2020.10.31
Spring 4일차 - Autowired  (0) 2020.10.23
Spring 3일차 - Container  (0) 2020.10.22
Comments