java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생

 

org.apache.catalina.startup.HostConfig deployDescriptor
심각: 배치 descriptor [C:\springstudy\apache-tomcat-8.5.73\conf\Catalina\localhost\app.xml]을(를) 배치하는 중 오류 발생
java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생

 

라이브러리 충돌로 인한 에러

 

 해결방법

 

1. [Project] - [Clean]

2. Tomcat v8.5 Server at localhost → Modules → 실행되고 있는 것 선택 후 Remove

3. Servers → Tomcat v8.5 Server at localhost 마우스로 우클릭 → Clean

4. 해당 Project 마우스로 우클릭 → [Maven] → Update Project... → 해당 프로젝트 체크 후 OK 버튼 마우스로 클릭

1. 서버 클린 : Servers > Tomcat > Clean & Clean Tomcat Work Directory
2. 프로젝트 클린 : Menu > Project > Clean
3. 메이븐 업데이트 : Project Explorer > 프로젝트 우클릭 > Maven > Update Project

 

 

4가지 방법 해봐도 안됨..

 

3월 21, 2022 4:19:32 오후 org.apache.catalina.startup.HostConfig deployDescriptor 심각: 배치 descriptor [C:\springstudy\apache-tomcat-8.5.73\conf\Catalina\localhost\app.xml]을(를) 배치하는 중 오류 발생 java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생

at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:673)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1881)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Caused by: org.apache.catalina.LifecycleException: 구성요소 [org.apache.catalina.webresources.StandardRoot@5b39f964]을(를) 시작하지 못했습니다.

at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4880)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5018)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
... 9 more

Caused by: java.lang.IllegalArgumentException: 지정된 주요 리소스셋 [C:\springstudy\apache-tomcat-8.5.73\webapps\app]은(는) 유효하지 않습니다.

at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:747)
at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:705)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
... 13 more

 

3월 21, 2022 4:40:09 오후 org.apache.catalina.core.StandardContext listenerStop
심각: 클래스 [org.springframework.web.context.ContextLoaderListener]의 인스턴스인 리스너에게 contextDestroyed 이벤트를 전송하는 중 예외 발생 java.lang.IllegalStateException: java.io.FileNotFoundException: C:\springstudy\apache-tomcat-8.5.73\webapps\spring16_mvc16_@ExceptionHandler\WEB-INF\lib\aspectjrt-1.6.10.jar (지정된 경로를 찾을 수 없습니다)
at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.getArchiveEntry
(AbstractSingleArchiveResourceSet.java:100)
at org.apache.catalina.webresources.AbstractArchiveResourceSet.getResource
(AbstractArchiveResourceSet.java:257) at org.apache.catalina.webresources.StandardRoot.getResourceInternal(StandardRoot.java:280)
at org.apache.catalina.webresources.Cache.getResource(Cache.java:62)
at org.apache.catalina.webresources.StandardRoot.getResource(StandardRoot.java:215)
at org.apache.catalina.webresources.StandardRoot.getClassLoaderResource(StandardRoot.java:224)
at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2365)
at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:876)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1379)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1223)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:117)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4811)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:844)
at org.apache.catalina.startup.HostConfig.undeploy(HostConfig.java:1458)
at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1383)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1646)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:314)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1170)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren
(ContainerBase.java:1396)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren
(ContainerBase.java:1400)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1368)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException:
C:\springstudy\apache-tomcat-8.5.73\webapps\spring16_mvc16_@ExceptionHandler\WEB-INF\lib\aspectjrt-1.6.10.jar (지정된 경로를 찾을 수 없습니다)
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:226)
at java.util.zip.ZipFile.<init>(ZipFile.java:155)
at java.util.jar.JarFile.<init>(JarFile.java:167)
at java.util.jar.JarFile.<init>(JarFile.java:131)
at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:202)
at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:187)
at org.apache.catalina.webresources.AbstractArchiveResourceSet.openJarFile
(AbstractArchiveResourceSet.java:308)
at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.getArchiveEntry
(AbstractSingleArchiveResourceSet.java:96)
... 24 more

 

 

경고: 호스트 appBase 내의 docBase [C:\springstudy\apache-tomcat-8.5.73\webapps\spring16_mvc13_mybatis]이(가) 지정되었으나, 이는 무시될 것입니다. 3월 21, 2022 5:22:06 오후 org.apache.catalina.core.ContainerBase addChildInternal 심각: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: 구성요소 [org.apache.catalina.webresources.StandardRoot@675b709e]을(를) 시작하지 못했습니다. at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4880) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5018) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:673) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1881) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.IllegalArgumentException: 지정된 주요 리소스셋 [C:\springstudy\apache-tomcat-8.5.73\webapps\app]은(는) 유효하지 않습니다. at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:747) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:705) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 13 more 3월 21, 2022 5:22:06 오후 org.apache.catalina.startup.HostConfig deployDescriptor 심각: 배치 descriptor [C:\springstudy\apache-tomcat-8.5.73\conf\Catalina\localhost\app.xml]을(를) 배치하는 중 오류 발생 java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생 at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:673) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1881) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.catalina.LifecycleException: 구성요소 [org.apache.catalina.webresources.StandardRoot@675b709e]을(를) 시작하지 못했습니다. at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4880) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5018) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) ... 9 more Caused by: java.lang.IllegalArgumentException: 지정된 주요 리소스셋 [C:\springstudy\apache-tomcat-8.5.73\webapps\app]은(는) 유효하지 않습니다. at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:747) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:705) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 13 more
3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext listenerStart 심각: Context initialized 이벤트를 [org.springframework.web.context.ContextLoaderListener] 클래스의 인스턴스인 리스너에 전송하는 동안 예외 발생 org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/tx] Offending resource: ServletContext resource [/WEB-INF/spring/root-context.xml] at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:118) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:110) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:301) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1432) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1419) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:172) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:142) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:126) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:614) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:514) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4763) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5232) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1177) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1925) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext startInternal 심각: 하나 이상의 리스너들이 시작하지 못했습니다. 상세 내역은 적절한 컨테이너 로그 파일에서 찾을 수 있습니다. 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext startInternal 심각: 이전 오류들로 인해 컨텍스트 [/spring16_mvc13_mybatis]의 시작이 실패했습니다. 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.ApplicationContext log 정보: Closing Spring root WebApplicationContext INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Mon Mar 21 17:22:26 KST 2022]; root of context hierarchy 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext listenerStop 심각: 클래스 [org.springframework.web.context.ContextLoaderListener]의 인스턴스인 리스너에게 contextDestroyed 이벤트를 전송하는 중 예외 발생 java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:164) at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1034) at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1009) at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:958) at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:583) at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:116) at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4811) at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5467) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:187) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1177) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1925) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)

 

 

 출처

 

https://zerowincoding.tistory.com/entry/%EC%9E%90%EC%8B%9D-%EC%BB%A8%ED%85%8C%EC%9D%B4%EB%84%88%EB%A5%BC-%EC%8B%9C%EC%9E%91%EC%A4%91-%EC%8B%A4%ED%8C%A8%ED%96%88%EC%8A%B5%EB%8B%88%EB%8B%A4

maven update

https://velog.io/@kchm0224/%EC%8A%A4%ED%94%84%EB%A7%81-%EA%B5%AC%EB%8F%99-%EC%98%A4%EB%A5%98-%ED%95%B4%EA%B2%B0

https://blog.studioego.info/3388

https://how-can-i.tistory.com/3

https://repacat.tistory.com/30

https://zelkun.tistory.com/entry/eclipse-javautilconcurrentExecutionException-orgapachecatalinaLifecycleException

+ 강의 교재

Server Tomcat v8.5 Server at localhost failed to start.

 

 

 해결방법

 

* Tomcat v8.5 Server at localhost → Server Options → Publish module contexts to separate XML files 체크 후 Ctrl + S (저장)

 

 

 

 출처

 

https://blog.naver.com/PostView.naver?blogId=starry_night1003&logNo=222134335543&parentCategoryNo=&categoryNo=7&viewDate=&isShowPopularPosts=true&from=search 

https://beagle-dev.tistory.com/76

+ 강의 교재

Port 8005 required by Tomcat v8.5 Server at localhost is already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).

 

 

간단한 코드 실행해보려 했는데, 바로 에러 발생

 

 해결 방법

 

1. CMD(명령 프롬프트)창 관리자 권한으로 실행 

Windows Key → CMD 검색 → 명령 프롬프트 앱 마우스로 우클릭 → 자세히 → 관리자 권한으로 실행

2. 

netstat -ano | findstr 8005

taskkill /F /pid ?????

netstat -ano | findstr 8005

 

 

 출처

 

https://devlimk1.tistory.com/151

+ 강의 교재

Spring Apache Tomcat Server 설정

 

Eclipse와 설정 방법이 비슷하다.

까먹어서 다시 정리해보자.

 

 Spring Apache Tomcat Server 설정

 

1.  STS3 실행 → Server 탭 → No servers are availavle. Click this link to create a new server... 마우스로 클릭

 

2. [New Server] → [Apache] → [Tomcat v8.5 Server] → Next 버튼 마우스로 클릭

3. [Tomcat installation directory] → Browse... 버튼 마우스로 클릭하여 apache-tomcat 8.5 저장된 경로 선택 

→ JRE: → Installed JREs... 버튼 클릭하여 설치한 jdk 버전 선택 → Finish 버튼 마우스로 클릭

4. Server 탭 → Tomcat v8.5 Server at localhost [Stopped, Republish] 마우스로 더블 클릭하여 실행

 

5. [Tomcat v8.5 Server at localhost] → [Server Locations] → Use Tomcat installation (takes control of Tomcat installation) 체크 → Deploy path:  → Browse... 버튼 클릭하여 apache-tomcat-8.5.xx\webapps 폴더 선택 후 Ctrl + s로 설정 저장

 

 출처

 

 

+ 강의 교재

 

해당 프로젝트 F5로 새로고침 진행해봐도 안되서 서버 삭제 후 새로 만듬

실습 5일차_AOP

 

 

 Spring AOP

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		UserService service = ctx.getBean("userService", UserService.class);
		System.out.println("반환값:"+ service.insert());

	}
}

MainClass2.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.DeptService;

public class MainClass2 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		DeptService service = ctx.getBean("deptService", DeptService.class);
		System.out.println("반환값:"+ service.selectList());

	}
}

MainClass3.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.DeptService;
import com.service.EmpService;

public class MainClass3 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		EmpService service = ctx.getBean("empService", EmpService.class);
		try {
		  service.update();
		}catch(Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
	}
}

MainClass4.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.EmpService;
import com.service.PersonService;

public class MainClass4 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		PersonService service = ctx.getBean("personService", PersonService.class);
		try {
		  String str = service.delete();
		  System.out.println("반환값:"+str);
		}catch(Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
	}
}

 

DeptServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class DeptServiceAspect {

	@AfterReturning(pointcut = "execution(* selectList(..))", returning = "retVal")
	public void doAccessCheck(Object retVal) {
		System.out.println("DeptServiceAspect.AfterReturning.selectList");
		System.out.println("리턴값:" + retVal);
	}
}

EmpServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

//부가기능 처리: aspect
@Aspect
public class EmpServiceAspect {

	@AfterThrowing(pointcut = "execution(* update(..))", throwing = "ex")
	public void doRecoveryActions(Exception ex) {
		System.out.println("EmpServiceAspect.AfterThrowing" 
	     + ex.getMessage());
	}
}

PersonServiceAspect.java

package com.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

//부가기능 처리: aspect
@Aspect
public class PersonServiceAspect {
 
		@Around("execution(* delete(..))")
	    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
	        System.out.println("Before Advice");
	        Object retVal = pjp.proceed();
	        System.out.println("After Advice");
	        System.out.println("retVal:" + retVal);
	        return retVal;
	    }
}

UserServiceAspect.java

package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

//부가기능 처리: aspect
@Aspect
public class UserServiceAspect {
  //1. pointcut와 advice 분리
	@Pointcut("execution(* list(..))")// the pointcut expression
	private void anyOldTransfer() {}// the pointcut signature
	
	@Before("anyOldTransfer()")
    public void doAccessCheck(JoinPoint point) {
		System.out.println("point:" + point);
		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.list");
    }
	
	//2. pointcut와 advice 합치기
	@Before("execution(* insert*(..))")
    public void doAccessCheck2(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.insert");
    }
	
	@After("execution(* insert*(..))")
    public void doAccessCheck3(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.AfterAdvice.insert");
    }
}

 

DeptService.java

package com.service;
import java.util.Arrays;
import java.util.List;

//타겟 (target object) ==> 핵심기능
public class DeptService {

	public List<String> selectList(){
		System.out.println("핵심기능:DeptService.selectList");
		return Arrays.asList("AAA","BBB");
	}
}

EmpService.java

package com.service;

//타겟 (target object) ==> 핵심기능
public class EmpService {

	public void update() {
		int num = 10/2;
		System.out.println("핵심기능:EmpService.update");
	}
}

PersonService.java

package com.service;

//타겟 (target object) ==> 핵심기능
public class PersonService {

	public String delete() {
		int num = 10/0;
		System.out.println("핵심기능:PersonService.insert");
		return "Hello";
	}
}

UserService.java

package com.service;

//타겟 (target object) ==> 핵심기능
public class UserService {

	//pointcut
	public String list() {
		return "UserService.list";
	}

	public String insert() {
		System.out.println("핵심기능:UserService.insert");
		return "UserService.insert";
	}
	public String insert2() {
		return "UserService.insert2";
	}	
}

user.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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<aop:aspectj-autoproxy />
	<!-- 1. BeforeAdvice와 AfterAdvice 실습 -->
	<bean id="userService" class="com.service.UserService" />
	<bean id="userAspect" class="com.aspect.UserServiceAspect" />
	
	<!-- 2. AfterReturningAdvice 실습 -->
	<bean id="deptService" class="com.service.DeptService" />
	<bean id="deptAspect" class="com.aspect.DeptServiceAspect" />
	
	<!-- 3 AfterThrowingAdvice 실습 -->
	<bean id="empService" class="com.service.EmpService" />
	<bean id="empAspect" class="com.aspect.EmpServiceAspect" />
	
	<!-- 4 AroundAdvice 실습 -->
	<bean id="personService" class="com.service.PersonService" />
	<bean id="personAspect" class="com.aspect.PersonServiceAspect" />
</beans>

 

* aop 추가 방법

[Namespaces] → [Configure Namespaces] 팝업창 OK 버튼 마우스로 클릭

 

* 출력 화면 

MainClass 출력화면

 

MainClass2 출력화면

 

MainClass3 출력화면

 

MainClass4 출력화면

 

 Spring AOP Component_Scan

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
			
		UserService service = ctx.getBean("userService", UserService.class);
		
		System.out.println(service.insert());
		//System.out.println(service.list());

	}
}

MainClass2.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.DeptService;
import com.service.UserService;

public class MainClass2 {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
				
		DeptService service2 = ctx.getBean("deptService", DeptService.class);
		System.out.println("반환값:" + service2.selectList());
		//System.out.println(service.list());
		
	}
}

MainClass3.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.EmpService;

public class MainClass3 {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
			
		EmpService service = ctx.getBean("empService", EmpService.class);
			
		try {
			service.update();
		} catch (Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
		
	}
}

MainClass4.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.EmpService;
import com.service.PersonService;

public class MainClass4 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		PersonService service = ctx.getBean("personService", PersonService.class);
		try {
		  String str = service.delete();
		  System.out.println("반환값:"+str);
		}catch(Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
	}
}

 

DeptServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DeptServiceAspect {

	@AfterReturning(pointcut = "execution(* selectList(..))", returning = "retVal")
	public void doAccessCheck(Object retVal) {
		System.out.println("DeptServiceAspect.AfterReturning.selectList");
		System.out.println("리턴값:" + retVal);
	}
}

EmpServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

//부가기능 처리: aspect
@Component
@Aspect
public class EmpServiceAspect {

	@AfterThrowing(pointcut = "execution(* update(..))", throwing = "ex")
	public void doRecoveryActions(Exception ex) {
		System.out.println("EmpServiceAspect.AfterThrowing" 
	     + ex.getMessage());
	}
}

PersonServiceAspect.java

package com.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

//부가기능 처리: aspect
@Component
@Aspect
public class PersonServiceAspect {
 
	 @Around("execution(* delete(..))")
	    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
	        System.out.println("Before Advice");
	        Object retVal = pjp.proceed();
	        System.out.println("After Advice");
	        System.out.println("retVal:" + retVal);
	        return retVal;
	    }
}

UserServiceAspect.java

package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//부가기능 처리: aspect
@Component
@Aspect
public class UserServiceAspect {
  //1. pointcut와 advice 분리
	@Pointcut("execution(* list(..))")// the pointcut expression
	private void anyOldTransfer() {}// the pointcut signature
	
	@Before("anyOldTransfer()")
    public void doAccessCheck(JoinPoint point) {
		System.out.println("point:" + point);
		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.list");
    }
	
	//2. pointcut와 advice 합치기
	@Before("execution(* insert*(..))")
    public void doAccessCheck2(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.insert");
    }
	
	@After("execution(* insert*(..))")
    public void doAccessCheck3(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.AfterAdvice.insert");
    }
}

 

DeptService.java

package com.service;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;

//타켓(target object) ==> 핵심기능
@Service
public class DeptService {
	public List<String> selectList(){
		System.out.println("핵심기능:DeptService.selectList");
		return Arrays.asList("AAA", "BBB");
	
	}
}

EmpService.java

package com.service;
import org.springframework.stereotype.Service;

//타켓(target object) ==> 핵심기능
@Service
public class EmpService {
	public void update() {
		int num = 10/2;
		System.out.println("핵심기능:EmpService.update");
	}
}

PersonService.java

package com.service;
import org.springframework.stereotype.Service;

// 타겟 (target object) ==> 핵심기능
@Service
public class PersonService {
	public String delete() {
		int num = 10/2;
		System.out.println("핵심기능:PersonSerivce.insert");
		return "Hello";
	}
}

UserService.java

package com.service;
import org.springframework.stereotype.Service;

// 타켓(target object) ==> 핵심기능
@Service
public class UserService {

	// pointcut
	public String list() {
		return "UserService.list";
	}
	
	public String insert() {
		return "UserService.insert";
	}
	
	public String insert2() {
		return "UserService.insert2";
	}
}

 

user.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	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">

	<aop:aspectj-autoproxy />
	<context:component-scan base-package="com.*"></context:component-scan>
</beans>

 

* 출력 화면 

MainClass 출력화면
MainClass2 출력화면
MainClass3 출력화면
MainClass4 출력화면

 

 출처

 

AOP : 

+ 강의 교재

 

실습 5일차_SpEL

 

https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/expressions.html

 

 Spring SpEL_Collection_Selection

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.ListPerson;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
			
		ListPerson listPerson = ctx.getBean("list1", ListPerson.class); //System.out.println(list1);
		List<Person> list1 = listPerson.getList();
		System.out.println("1. 전체 데이터 출력");
		
		for (Person person : list1) {
			System.out.println(person);
		}
		
		ListPerson listPerson2 = ctx.getBean("list2", ListPerson.class); //System.out.println(list1);
		List<Person> list2 = listPerson2.getList();
		System.out.println("2. SpEL 전체 데이터 출력");
		for (Person person : list2) {
			System.out.println(person);
		}
		
		ListPerson listPerson3 = ctx.getBean("list3", ListPerson.class); //System.out.println(list1);
		List<Person> list3 = listPerson3.getList();
		System.out.println("3. SpEL 특정 인덱스 데이터 출력");
		for (Person person : list3) {
			System.out.println(person);
		}
		
		ListPerson listPerson4 = ctx.getBean("list4", ListPerson.class); //System.out.println(list1);
		List<Person> list4 = listPerson4.getList();
		System.out.println("4. SpEL 조건 데이터 출력");
		for (Person person : list4) {
			System.out.println(person);
		}
		
		ListPerson listPerson5 = ctx.getBean("list5", ListPerson.class); //System.out.println(list1);
		List<Person> list5 = listPerson5.getList();
		System.out.println("5. SpEL 멀티 조건 데이터 출력");
		for (Person person : list5) {
			System.out.println(person);
		}
	}
}

ListPerson.java

package com.dto;
import java.util.List;

public class ListPerson {

	List<Person> list;

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "ListPerson [list=" + list + "]";
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<util:list id="personList">
		<bean id="p1" class="com.dto.Person" p:username="고길동" p:age="30" p:married="true" p:weight="50" />
		<bean id="p2" class="com.dto.Person" p:username="신길동" p:age="40" p:married="false" p:weight="60" />
		<bean id="p3" class="com.dto.Person" p:username="홍길동" p:age="10" p:married="false" p:weight="70" />
		<bean id="p4" class="com.dto.Person" p:username="이길동" p:age="25" p:married="true" p:weight="60" />
	</util:list>
	
	<bean id="list1" class="com.dto.ListPerson">
		<property name="list" ref="personList" />
	</bean>
	
	<!-- SpEL -->
	<bean id="list2" class="com.dto.ListPerson">
		<property name="list" value="#{personList}"/>
	</bean> 
	
	<!-- SpEL -->
	<bean id="list3" class="com.dto.ListPerson">
		<property name="list" value="#{personList[1]}"/>
	</bean> 
	
	<!-- SpEL -->
	<!-- 행선택(selection) 문법 ===> 참조값.?[조건식] -->
	<bean id="list4" class="com.dto.ListPerson">
		<property name="list" value="#{personList.?[age > 25]}"/>
	</bean> 
	
	<!-- SpEL -->
	<!-- 행선택(selection) 문법 ===> 참조값.?[조건식 and 조건식 or 조건식] -->
	<bean id="list5" class="com.dto.ListPerson">
		<property name="list" value="#{personList.?[age > 25 and married == true]}"/>
	</bean>

</beans>

* 출력 화면 

 

 Spring SpEL_Collection_Projection

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.ListPerson;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		ListPerson listPerson1 = ctx.getBean("list1", ListPerson.class);
	    List<String> usernameList = listPerson1.getUsernameList();
	    System.out.println("1. username 프라퍼티 전체 출력");
	    for (String name : usernameList) {
			System.out.println(name);
		}
	
	    ListPerson listPerson2 = ctx.getBean("list2", ListPerson.class);
	    List<Integer> ageList = listPerson2.getAgeList();
	    System.out.println("2. age 프라퍼티 전체 출력");
	    for (int age : ageList) {
			System.out.println(age);
		}
	
	}
}

ListPerson.java

package com.dto;
import java.util.List;

public class ListPerson {

	// selection
	List<Person> list;
	
	// projection
	List<String> usernameList;
	List<Integer> ageList;
	
	public List<String> getUsernameList() {
		return usernameList;
	}

	public void setUsernameList(List<String> usernameList) {
		this.usernameList = usernameList;
	}

	public List<Integer> getAgeList() {
		return ageList;
	}

	public void setAgeList(List<Integer> ageList) {
		this.ageList = ageList;
	}

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "ListPerson [list=" + list + "]";
	}
	
}

Person.java

package com.dto;

public class Person {

	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
}

user.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:util="http://www.springframework.org/schema/util"
	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/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<util:list id="personList">
	   <bean id="p1" class="com.dto.Person" p:username="홍길동" p:age="30" p:married="true" p:weight="78.6" />
	   <bean id="p2" class="com.dto.Person" p:username="고길동" p:age="40" p:married="false" p:weight="100.2" />
	   <bean id="p3" class="com.dto.Person" p:username="신길동" p:age="10" p:married="false" p:weight="56.2" />
	   <bean id="p4" class="com.dto.Person" p:username="이길동" p:age="23" p:married="true" p:weight="75.6" />
	</util:list>
	
	 <!-- 
	   selection 문법:  참조변수.?[조건식] , 참조변수.?[조건식 and 조건식 or 조건식] 
	 -->
	 
	 <!-- 
	     projection 문법:  참조변수.![property]  
	 -->
	 <bean id="list1" class="com.dto.ListPerson">
	   <property name="usernameList" value="#{personList.![username]}" />
	 </bean>
	 
	 <bean id="list2" class="com.dto.ListPerson">
	   <property name="ageList" value="#{personList.![age]}" />
	 </bean>
</beans>

* 출력 화면 

 

 Spring SpEL_Collection_Selection & Projection

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.ListPerson;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		ListPerson listPerson1 = ctx.getBean("list1", ListPerson.class);
	    List<String> usernameList = listPerson1.getUsernameList();
	    System.out.println("1. username 프라퍼티 조건 출력");
	    for (String name : usernameList) {
			System.out.println(name);
		}
	
	    ListPerson listPerson2 = ctx.getBean("list2", ListPerson.class);
	    List<Integer> ageList = listPerson2.getAgeList();
	    System.out.println("2. age 프라퍼티 조건 출력");
	    for (int age : ageList) {
			System.out.println(age);
		}
	
	}
}

ListPerson.java

package com.dto;
import java.util.List;

public class ListPerson {
	
	// selection
	List<Person> list;
	
	// projection
	List<String> usernameList;
	List<Integer> ageList;
	
	public List<String> getUsernameList() {
		return usernameList;
	}

	public void setUsernameList(List<String> usernameList) {
		this.usernameList = usernameList;
	}

	public List<Integer> getAgeList() {
		return ageList;
	}

	public void setAgeList(List<Integer> ageList) {
		this.ageList = ageList;
	}

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "ListPerson [list=" + list + ", usernameList=" + usernameList + ", ageList=" + ageList + "]";
	}

}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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:util="http://www.springframework.org/schema/util"
	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/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<util:list id="personList">
	   <bean id="p1" class="com.dto.Person" p:username="고길동" p:age="30" p:married="true" p:weight="78.6" />
	   <bean id="p2" class="com.dto.Person" p:username="신길동" p:age="40" p:married="false" p:weight="100.2" />
	   <bean id="p3" class="com.dto.Person" p:username="홍길동" p:age="10" p:married="false" p:weight="56.2" />
	   <bean id="p4" class="com.dto.Person" p:username="이길동" p:age="23" p:married="true" p:weight="75.6" />
	</util:list>
	
	 <!-- 
	   selection 문법:  참조변수.?[조건식] , 참조변수.?[조건식 and 조건식 or 조건식] 
	 -->
	 
	 <!-- 
	     projection 문법:  참조변수.![property]  
	 -->
	 
	 <!-- 
	     selection 및 projection 조합
	         ==> 참조변수.?[조건식].![property]
	  -->
	 <bean id="list1" class="com.dto.ListPerson">
	   <property name="usernameList" value="#{personList.?[age > 25].![username]}" />
	 </bean>
	 
	 <bean id="list2" class="com.dto.ListPerson">
	   <property name="ageList" value="#{personList.?[married==true].![age]}" />
	 </bean>
</beans>

 

* 출력 화면 

 

 출처

 

 

+ 강의 교재

 

실습 5일차_SpEL

 

SpEL - Spring Expression Language
Spring Expression Language는 보통 SpEL로 표기하며 구두로는 Spring EL이라고 지칭한다.
SpEL은 보통 객체를 조회하고 조작하는 기능을 제공하여 Unified EL과 유사하지만
Method 호출, 문자열 템플릿 기능 등의 여러가지 추가 기능을 제공하는 표현식 언어이다.
Spring 3.0부터 지원된다.

 

 Spring SpEL 

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean isMarried;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return isMarried;
	}
	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", isMarried=" + isMarried + ", weight=" + weight
				+ "]";
	}
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL -->
	<bean id="p2" class="com.dto.Person">
		<property name="username" value="#{'신길동'}" />
		<property name="age" value="#{20+10}" />
		<property name="married" value="#{10>4}" />
		<property name="weight" value="#{'75.75'}" />
	</bean>
	
</beans>

 

* 출력 화면 

 

 Spring SpEL_ref 

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {

	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
	}
}

Cat.java

package com.dto;

public class Cat {

	String name;
	int age;
	String sex;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}

}

Person.java

package com.dto;

public class Person {

	String username;
	int age;
	boolean isMarried;
	double weight;
	
	Cat cat;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean isMarried() {
		return isMarried;
	}

	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}

	public double getWeight() {
		return weight;
	}

	public void setWeight(double weight) {
		this.weight = weight;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", isMarried=" + isMarried + ", weight=" + weight
				+ ", cat=" + cat + "]";
	}
	
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="c1" class="com.dto.Cat">
	  <property name="name" value="나비" />
	  <property name="age" value="2" />
	  <property name="sex" value="암컷" />
	</bean>

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="57.25" />
		<property name="cat" ref="c1" />  <!-- ref 이전 -->		
	</bean>

    <bean id="p2" class="com.dto.Person">
		<property name="username" value="홍길동" />
		<property name="age" value="30" />
		<property name="married" value="true" />
		<property name="weight" value="77.77" />
		<property name="cat"  value="#{c1}"/>  <!-- SpEL -->  		
	</bean>
</beans>

* 출력 화면 

 

 Spring SpEL_property

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public boolean getMarried() {
		return married;
	}
	
	public void setMarried(boolean married) {
		married = married;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL --> <!-- 다른  bean에 있는 property 값 접근할 수 있음 -->
	<bean id="p2" class="com.dto.Person">
		<property name="username" value="#{p1.username}" />
		<property name="age" value="#{p1.age+10}" />
		<property name="married" value="#{p1.married}" />
		<property name="weight" value="#{p1.weight}" />
	</bean>
	
</beans>

* 출력 화면 

 

 Spring SpEL_method

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p1 = ctx.getBean("p1", Person.class);
		System.out.println(p1);
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
		Person p4 = ctx.getBean("p4", Person.class);
		System.out.println(p4);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public boolean getMarried() {
		return married;
	}
	
	public void setMarried(boolean married) {
		married = married;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
	// 필요에 의해서 추가된 메서드
	public String getName() {
		return "GOKilDong";

	}
	
	public String getName2() {
		//return "GOKilDong";
		return null;
	}
	
	// static 메서드
	public static String getName3() {
		return "Park";
	}
	
}

user.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
										  <!-- 일반 메서드 호출 방법 -->
	<bean id="p1" class="com.dto.Person"> <!-- 필요에 의해서 추가된 메서드에도 접근할 수 있다. SpEL로 메서드 호출 가능 -->
		<property name="username" value="#{p1.getName()}" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL --> <!-- 다른  bean에 있는 property 값 접근할 수 있음 -->
	<bean id="p2" class="com.dto.Person"> 
		<property name="username" value="#{p1.getName().toUpperCase()}" />
		<property name="age" value="#{p1.age}" />
		<property name="married" value="#{p1.married}" />
		<property name="weight" value="#{p1.weight}" />
	</bean>
	
	<bean id="p3" class="com.dto.Person"> 
		<property name="username" value="#{p1.getName2()?.toUpperCase()}" /><!-- 에러 방지? -->
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<bean id="p4" class="com.dto.Person"> <!-- static 메서드 호출 방법 -->
		<property name="username" value="#{T(com.dto.Person).getName3()}" /><!-- .java가 아니기에 pakage명까지 넣어줘야 함 -->
		<property name="age" value="#{T(java.lang.Math).random()+1 * 10.0}" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
</beans>

* 출력 화면 

 

 출처

 

SpEL : https://atoz-develop.tistory.com/entry/Spring-SpEL-Spring-Expression-Language

+ 강의 교재

 

실습 4일차_MyBatis_Transaction ★

 

 Spring MyBatis_Transaction ★

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.DeptDTO;
import com.service.DeptService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/dept.xml");	
		DeptService service = ctx.getBean("deptService", DeptService.class);
		
		// 1. 저장 ==> Spring + Mybatis는 자동으로 commit된다.
		// int num = service.insert(new DeptDTO(99, "IT", "부산"));	
		// int num2 = service.update(new DeptDTO(99, "AI", "서울"));
		// int num3 = service.delete(99);
		
		// transaction 처리	
		try {
			service.tx();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		List<DeptDTO> list = service.selectAll();
		System.out.println(list);
	}
}

DeptDAO.java

package com.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dto.DeptDTO;

@Repository("deptDAO")
public class DeptDAO {
	
	@Autowired
	SqlSession session; // null
	// SqlSessionTemplate session;
	
	public List<DeptDTO> selectAll(){
		return session.selectList("com.config.DeptMapper.selectAll");
	}

	public DeptDTO selectByDeptno(int deptno) {
		
		return session.selectOne("com.config.DeptMapper.selectByDeptno", deptno);
	}

	public int insert(DeptDTO dto) {
		
		return session.insert("com.config.DeptMapper.insert", dto);
	}

	public int update(DeptDTO dto) {
		
		return session.update("com.config.DeptMapper.update", dto);
	}
	
	public int delete(int deptno) {
		
		return session.delete("com.config.DeptMapper.delete", deptno);
	}
}

DeptDTO.java

package com.dto;
import org.apache.ibatis.type.Alias;

@Alias("DeptDTO")
public class DeptDTO {

	int deptno;
	String dname;
	String loc;
	
	public DeptDTO() {
		
	}
	
	public DeptDTO(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
	@Override
	public String toString() {
		return "DeptDTO [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}
}

DeptService.java

package com.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.dto.DeptDTO;

@Service("deptService")
public interface DeptService {

	// 전체 레코드 조회
	public List<DeptDTO> selectAll();
	
	// 특정 레코드 조회
	public DeptDTO selectByDeptno(int deptno);
	
	// 저장
	public int insert(DeptDTO dto);
	
	// 수정
	public int update(DeptDTO dto);
	
	// 삭제
	public int delete(int deptno);
	
	// 트랜잭션 실습 메서드
	public void tx() throws Exception;
	
}

DeptServiceImpl.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.DeptDAO;
import com.dto.DeptDTO;

@Service("deptService")
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	DeptDAO dao; //null

	@Override
	public List<DeptDTO> selectAll() {
		
		return dao.selectAll();
	}

	@Override
	public DeptDTO selectByDeptno(int deptno) {
		
		return dao.selectByDeptno(deptno);
	}

	@Override
	public int insert(DeptDTO dto) {
		
		return dao.insert(dto);
	}

	@Override
	public int update(DeptDTO dto) {
		
		return dao.update(dto);
	}
	
	@Override
	public int delete(int deptno) {
		
		return dao.delete(deptno);
	}

	// 트랜잭션 실습 메서드
	@Transactional
	@Override
	public void tx() throws Exception {
		int num = dao.insert(new DeptDTO(96, "IT", "서울"));
		int num2 = dao.delete(1);
	}
}

dept.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: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">

  <!-- mybatis 연동 -->
  <!-- 1. jdbc.properties 등록 -->
  <context:property-placeholder location="classpath:com/config/jdbc.properties"/>

  <!-- 2. DBCP2 등록 (Connection Pool 기능을 가지고 있음) -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.oracle}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.userid}" />
    <property name="password" value="${jdbc.passwd}" />
  </bean>
  
  <!-- 트랜잭션 처리 -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
  <tx:annotation-driven transaction-manager="txManager"/>
  <!-- 트랜잭션 처리 -->
  
  <!-- 3. SqlSessionFactoryBean 등록 -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
		<value>classpath:com/config/DeptMapper.xml</value>      
      </list>
    </property>
    <property name="typeAliases">
      <list>
        <value>com.dto.DeptDTO</value>
      </list>
    </property>
  </bean>
  
  <!-- 4. SqlSessionTemplate 등록 -->
  <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
  </bean>
  <!-- mybatis 연동 -->
  <context:component-scan base-package="com.*" />

</beans>

DeptMapper.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.config.DeptMapper">

	<select id="selectAll" resultType="DeptDTO">
	<![CDATA[
		select deptno,dname,loc
		from dept
		order by deptno desc
		]]>
	</select>
	
	<select id="selectByDeptno" resultType="DeptDTO"
		parameterType="int">
		<![CDATA[
		select deptno,dname,loc
		from dept
		where deptno = #{deptno}
		]]>
	</select>
	
	<insert id="insert" parameterType="DeptDTO">
	<![CDATA[
	    insert into dept ( deptno, dname, loc )
	    values ( #{deptno} , #{dname} , #{loc})
	    ]]>
	</insert>
	
	<update id="update" parameterType="DeptDTO">
	<![CDATA[
	   update dept 
	   set dname = #{dname} , loc=#{loc}
	   where deptno = #{deptno}
	   ]]>
	</update>
	
	<delete id="delete" parameterType="int">
	<![CDATA[
	   delete from dept
	   where deptno = #{deptno}
	   ]]>
	</delete>

</mapper>

jdbc.properties

#주석입니다.
#문법은 key=value
jdbc.oracle=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=????? #DB 계정
jdbc.passwd=????? #DB 계정 패스워드

 

* 출력 화면 

 

 출처

 

Mybatis : 

+ 강의 교재

 

실습 4일차_MyBatis ★

 

 Spring MyBatis ★

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.DeptDTO;
import com.service.DeptService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/dept.xml");
		
		DeptService service = ctx.getBean("deptService", DeptService.class);
		
		// 1. 저장 ==> Spring + Mybatis는 자동으로 commit된다.
		// int num = service.insert(new DeptDTO(99, "IT", "부산"));
		// int num2 = service.update(new DeptDTO(99, "AI", "서울"));
		// int num3 = service.delete(99);
		
		List<DeptDTO> list = service.selectAll();
		System.out.println(list);
	}
}

DeptDAO.java

package com.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dto.DeptDTO;

@Repository("deptDAO")
public class DeptDAO {
	
	@Autowired
	SqlSession session; // null
	// SqlSessionTemplate session;
	
	public List<DeptDTO> selectAll(){
		return session.selectList("com.config.DeptMapper.selectAll");
	}
	
	public DeptDTO selectByDeptno(int deptno) {
		
		return session.selectOne("com.config.DeptMapper.selectByDeptno", deptno);
	}

	public int insert(DeptDTO dto) {
		
		return session.insert("com.config.DeptMapper.insert", dto);
	}

	public int update(DeptDTO dto) {
		
		return session.update("com.config.DeptMapper.update", dto);
	}
	
	public int delete(int deptno) {
		
		return session.delete("com.config.DeptMapper.delete", deptno);
	}
}

DeptDTO.java

package com.dto;
import org.apache.ibatis.type.Alias;

@Alias("DeptDTO")
public class DeptDTO {

	int deptno;
	String dname;
	String loc;
	
	public DeptDTO() {
		
	}
	
	public DeptDTO(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
	@Override
	public String toString() {
		return "DeptDTO [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}
	
}

DeptService.java

package com.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.dto.DeptDTO;

@Service("deptService")
public interface DeptService {

	// 전체 레코드 조회
	public List<DeptDTO> selectAll();
	
	// 특정 레코드 조회
	public DeptDTO selectByDeptno(int deptno);
	
	// 저장
	public int insert(DeptDTO dto);
	
	// 수정
	public int update(DeptDTO dto);
	
	// 삭제
	public int delete(int deptno);
}

DeptServiceImpl.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.DeptDAO;
import com.dto.DeptDTO;

@Service("deptService")
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	DeptDAO dao; //null

	@Override
	public List<DeptDTO> selectAll() {
		
		return dao.selectAll();
	}

	@Override
	public DeptDTO selectByDeptno(int deptno) {
		
		return dao.selectByDeptno(deptno);
	}

	@Override
	public int insert(DeptDTO dto) {
		
		return dao.insert(dto);
	}

	@Override
	public int update(DeptDTO dto) {
		
		return dao.update(dto);
	}
	
	@Override
	public int delete(int deptno) {
		
		return dao.delete(deptno);
	}

}

dept.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"
	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">

  <!-- mybatis 연동 -->
  <!-- 1. jdbc.properties 등록 -->
  <context:property-placeholder location="classpath:com/config/jdbc.properties"/>

  <!-- 2. DBCP2 등록 (Connection Pool 기능을 가지고 있음) -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.oracle}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.userid}" />
    <property name="password" value="${jdbc.passwd}" />
  </bean>
  
  <!-- 3. SqlSessionFactoryBean 등록 -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
		<value>classpath:com/config/DeptMapper.xml</value>      
      </list>
    </property>
    <property name="typeAliases">
      <list>
        <value>com.dto.DeptDTO</value>
      </list>
    </property>
  </bean>
  
  <!-- 4. SqlSessionTemplate 등록 -->
  <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
  </bean>
  <!-- mybatis 연동 -->
  <context:component-scan base-package="com.*" />

</beans>

DeptMapper.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.config.DeptMapper">

	<select id="selectAll" resultType="DeptDTO">
	<![CDATA[
		select deptno,dname,loc
		from dept
		order by deptno desc
		]]>
	</select>
	
	<select id="selectByDeptno" resultType="DeptDTO"
		parameterType="int">
		<![CDATA[
		select deptno,dname,loc
		from dept
		where deptno = #{deptno}
		]]>
	</select>
	
	<insert id="insert" parameterType="DeptDTO">
	<![CDATA[
	    insert into dept ( deptno, dname, loc )
	    values ( #{deptno} , #{dname} , #{loc})
	    ]]>
	    
	</insert>
	
	<update id="update" parameterType="DeptDTO">
	<![CDATA[
	   update dept 
	   set dname = #{dname} , loc=#{loc}
	   where deptno = #{deptno}
	   ]]>
	</update>
	
	<delete id="delete" parameterType="int">
	<![CDATA[
	   delete from dept
	   where deptno = #{deptno}
	   ]]>
	</delete>

</mapper>

jdbc.properties

#주석입니다.
#문법은 key=value
jdbc.oracle=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=????? #DB 계정
jdbc.passwd=????? #DB 계정 패스워드

 

* 출력 화면 

 

 출처

 

Mybatis : 

+ 강의 교재

 

실습 4일차_Component_Scan

 

 

 

 Spring Component_Scan

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		List<String> list = service.list();
		System.out.println(list);
	}
}

UserDAO.java

package com.dao;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

// @Component // @Component는 전부 Class Level
@Repository("dao")
public class UserDAO {
	
	public UserDAO() {
		System.out.println("UserDAO 생성자");
	}

	// DB 연동 가정
	public List<String> list(){
		List<String> list = Arrays.asList("고길동", "홍길동", "신길동");
		return list;
	}
}

UserService.java

package com.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.dao.UserDAO;

// POJO Class
// @Component // @Component는 전부 Class Level
@Service("service")
public class UserService {
	
	@Autowired
	UserDAO dao; // property (인스턴스 변수)
	
	public UserService() {
		System.out.println("UserService 생성자");
	}
	
	public List<String> list(){
		return dao.list();
	}
}

user.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"
	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:annotation-config /> --> <!-- empty tag -->
	
	<!-- 내부적으로 <context:annotation-config /> 기능 포함 -->

	<!-- 마킹된(Component) Bean들의 Pakage Name 지정 -->
	<context:component-scan base-package="com.service, com.dao" /> <!-- empty tag -->
	<!-- <context:component-scan base-package="com.*" /> -->
</beans>
<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

 

* 출력 화면 

 

 출처

 

* Component_Scan : 

+ 강의 교재

 

실습 4일차_@Value_resourceBundle

 

 

 

 Spring @Value_resourceBundle

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Cat c = ctx.getBean("cat1", Cat.class);
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());	
	}
}

Cat.java

package com.dto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class Cat {
	
	@Value("${cat.name}")
	String name;
	@Value("${cat.age}")
	int age;
	@Value("${cat.sex}")
	String sex;
	
	public Cat() {

	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	
	String username;
	int userage;
	String address;
	
	//@Autowired(required = false)
	//@Qualifier("cat1")
	@Resource(name = "cat2")
	Cat cat; // null
	
	public Person() {
	
	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

test.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"
	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:annotation-config />

	<context:property-placeholder location="classpath:com/config/cat.properties" file-encoding="utf-8"/> 

	<bean id="cat1" class="com.dto.Cat" />
	<!-- 
	<bean id="cat1" class="com.dto.Cat"> < 생성자로 주입   property라는 setter method 이용-->
		<!-- 	<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	 -->

</beans>

 

<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

cat.properties

cat.name = 망치 
cat.age = 2
cat.sex = 수컷

 

* 출력 화면 

 

 출처

 

@Value: 

+ 강의 교재

 

+ Recent posts