드라이브 c -> spring 폴더 생성 -> Java program 에서 sts3.9.14 폴더 끌고 와서 압축풀기
springSrc 폴더 생성 (스프링소스백업파일)
sever에서 떠있는거 delect
sever 설정
window->
preferences
web browser - chrome
workspace other ->utp-8
wep --> css,html,jsp utp-8로 다 맞추기
대표적 오픈소스기반의 어플리케이션 프레임워크
EJB 의복잡성및 빈약한 데이터 모델을 해결 하기위한 POJO 기반 의 OSS 프레임워크
1) CORE: IoC, DI, DDD를 기반으로하는 디자인 패턴
2) MVC : 웹어플리케이션 제작을 위한 기반제공
3) AOP : 프록시기반의 AOP 기반 인프라 제공
4) ORM : Hibernate, iBatis의3rdParty 플러그인 제공
5) DAO: 데이터를 액세스하기 위한 기반제공
스프링의 대표적인 기술 4가지 -- 면접질문
DI
AOP
Spring MVC
ORM
IOC Inversion of control
기존의 프로그래밍에서 객체의 생성, 제어, 소멸 등의 객체의 라이프 사이클을
개발자가 관리 하던 것을 컨테이너 에게 그 제어권을 위임하는 프로그래밍 기법
[1] DL(Dependency Lookup)
[2] DI(Dependency Injection) ** spring 에선 거의 DI사용
의존성 주입
각 계층 사이, 각 클래스 사이에 필요로 하는 의존 관계를 컨테이너가 자동으로 연결해 주는 것
종류
Setter Injection <setter방식>,
Constructor Injection <생성자방식>,
Method Injection <두개혼합한방식>
Spring -- Legacy/ boot
POM.XML 에서 입력하면 --> Maven Dependencies 에서 알아서 다운로드
POM.XML 자동으로 다운로드 되어지는소스
POM.XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oracle</groupId> --회사이름
<artifactId>och01_di01</artifactId> --프로젝트 정보
<version>0.0.1-SNAPSHOT</version> --버전
<description>DI</description>
--이모듈들을 사용할거라고 입력하는 순간 알아서 다운로드되어짐 --
-- 자동으로 다운로드 되어지는소스 --
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
</dependencies>
</project>
pom과 Maven dependencie 는 한팀
package sam01;
public class MessageBeanKo {
void sayHello(String name) {
System.out.println(name+"안녕");
}
}
package MessageBeanEn.sam01;
public class MessageBeanEn {
void sayHello(String name) {
System.out.println(name+"Hello");
}
}
EX01 -->실행파일
EX01.java
package sam01;
import javax.management.MBeanAttributeInfo;
public class Ex01 {
public static void main(String[] args) {
// MessageBeanEn mb = new MessageBeanEn();
MessageBeanKo mb = new MessageBeanKo ();
mb.sayHello("spring");
}
}
package sam02;
public interface MessageBean {
void sayHello(String name);
}
package sam02;
public class MessageBeanEn implements MessageBean {
public void sayHello(String name) {
// 상속받아서 만듬
System.out.println(name+"! Hello");
}
}
package sam02;
public class MessageBeanKo implements MessageBean {
// 상속받아서 만듬
public void sayHello(String name) {
System.out.println(name + "안녕하세요");
}
}
Ex02.java
package sam02;
public class Ex02 {
public static void main(String[] args) {
// MessageBean mb = new MessageBeanKo();
MessageBean mb = new MessageBeanEn();
mb.sayHello("spring");
}
}
DI방식 (Dependency Injection)
MessageBeanjava
package sam03;
public interface MessageBean {
void sayHello();
}
MessageBeanlmpl.java
package sam03;
public class MessageBeanlmpl implements MessageBean {
private String name;
private String greet;
public MessageBeanlmpl (String name , String greet) {
this.name = name;
this.greet = greet;
}
public void sayHello() {
// TODO Auto-generated method stub
System.out.println(name + "님!! " + greet);
}
}
Ex03.java
package sam03;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Ex03 {
public static void main(String[] args) {
//기본
MessageBean cmb = new MessageBeanlmpl("허유나","기본적 안녕");
cmb.sayHello();
// DI 호출객체를 사용함
//환경과 프로그램을 주고 받을때 --> comtext
ApplicationContext ac = new ClassPathXmlApplicationContext("bean03.xml"); //선언하고
//bean03.xml에 있는 파일을 읽어서 가져온다
MessageBean mb = (MessageBean) ac.getBean("mb3"); //mb3받을때 타입이 뭔지 적어주기 //선언한거 가져와서
mb.sayHello(); //사용
}
}
bean03 실행시켜주는 파일 생성
new -> spring Bean Definition file에서 생성
Bean03.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">
<!-- beans안에 bean을 설정 -->
<bean id="mb3" class="sam03.MessageBeanlmpl">
<!-- set이 없으면 생성자를 통해 주입
생성자 arg 값 -->
<constructor-arg><value>홍성대</value> </constructor-arg>
<constructor-arg value="메리 크리스마스"></constructor-arg>
</bean>
</beans>
MessageBeanImpl의 값을 xml에 set이 없으면 생성자를 통해 값을 주입함
MessageBean.java
package sam05;
public interface MessageBeam {
void sayHello();
}
class
messageBean sma05상속받아서 만들기
MessageBeanImpl.java
package sam05;
public class MessageBeanImpl implements MessageBeam {
public String name;
public String greet;
-----getter setter 셋팅해주고
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGreet() {
return greet;
}
public void setGreet(String greet) {
this.greet = greet;
}
-----출력
public void sayHello() {
System.out.println(name +"님"+ greet+ " !! ");
}
}
출력할 실행파일
Ex05.java
package sam05;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Ex05 {
public static void main(String[] args) {
//기본방식
MessageBeanImpl mb5 = new MessageBeanImpl();
mb5.setGreet("Goodbye");
mb5.setName("한창훈");
//setter호출객체 사용
ApplicationContext ac = new ClassPathXmlApplicationContext("bean05.xml");
MessageBeam mb = (MessageBeam) ac.getBean("mb5");
mb.sayHello();
}
}
bean05.xml 의 리소스 만들기
new -> spring Bean Definition file에서 생성
bean05.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="mb5" class="sam05.MessageBeanImpl"> <!-- 이클라스를 mb5라고 선언하고 쓰겠다 -->
<property name="name"><value> 한창훈</value> </property>
<property name="greet" value="Good Bye"></property>
</bean>
</beans>
name은 설정해준 이름 그대로 적어주기
getter방식일때는 생성자 constructor-arg 사용
setter방식으로 이용할때는 property 사용
vehicle.java
package sam06;
public interface vehicle {
void ride() ;
}
(생성자 property 2가지 사용하기위해서 ride랑 speed 의 setter 만 설정해두었음 )
package sam06;
public class VehicleImpl implements vehicle {
private String name;
private String rider;
private int speed;
/* ride랑 speed setter 만 넣기 */
public VehicleImpl(String name) {
this.name=name;
}
public void setRider(String rider) {
this.rider = rider;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void ride() {
System.out.println(name + "님은(는)" +rider+ "를 이용" +speed+ "km속도를 탄다 ");
}
}
실행파일
Ex06.java
package sam06;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Ex06 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean06.xml");
vehicle vh = (vehicle) ac.getBean("vh7");
vh.ride();
}
}
bean06.xml셋팅해주기
bean06.xm
<?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="mb6" class="sam06.VehicleImpl">
<constructor-arg value="한의정"></constructor-arg>
<property name="ride" value="벤츠"></property>
<property name="speed" value="300"></property>
</bean>
</beans>
출력 : 한의정님은(는)벤츠를 이용300km속도를 탄다
인터페이스 2개 생성
MessageBean.java
package sam07;
public interface MessageBean {
void sayHello();
}
Outputter.java
package sam07;
public interface Outputter {
void output(String msg);
}
인터페이스 상속받아서 class 2개 만들기
MessageBeanImpl.java
package sam07;
public class MessageBeanImpl implements MessageBean {
private String name;
private String greet;
private Outputter outputter ;
public void setName(String name) {
this.name = name;
}
public void setGreet(String greet) {
this.greet = greet;
}
public void setOutputter(Outputter outputter) {
this.outputter = outputter;
}
public void sayHello() {
String msg = name+"님!! " + greet;
System.out.println(msg); //msp출력되어지고
if(outputter!=null) outputter.output(msg); //outputter로 msg 가 들어가서 실행됨
}
}
-----------------------------------------
FileOutputter.java
package sam07;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileOutputter implements Outputter {
private String fileName;
public void setFileName(String fileName) {
this.fileName = fileName;
}
최혜선님 !! 클래식
public void output(String msg) {
try {
System.out.println("filename:" + fileName);
FileWriter fw = new FileWriter(new File(fileName));
fw.write(msg); //파일생성하고
fw.close(); //파일종료
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
실행파일
HelloApp.java
package sam07;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloApp {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("/sam07/bean07.xml"); /* 여기다 넣어서 사용가능 */
MessageBean mb = (MessageBean) ac.getBean("mb7");
mb.sayHello();
}
}
private Outputter outputter ;
//객체를 DI로 선언할때 REPERENCE로 넘겨줌
bean07.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="outputter" class="sam07.FileOutputter">
<property name="fileName" value="c:/log/msg1.txt"></property>
</bean>
<bean id="mb7" class="sam07.MessageBeanImpl">
<property name="name" value="최혜선"></property>
<property name="greet" ><value> 클래식</value> </property>
<!-- 객체를 DI로 선언할때 주소값을 넘겨줘야 하기때문에 REPERENCE로 넘겨받음 -->
<property name="outputter"><ref bean="outputter" ></ref></property>
//위에 id랑 bean이랑 이름 똑같아야함
</bean>
</beans>
Calculator.java
package DI01;
public class Calculator {
public void addition(int f, int s) {
System.out.println("addition()");
int result = f +s;
System.out.println(f + " + " + s + " = " + result);
}
public void substraction (int f, int s) {
System.out.println("substraction()");
int result = f -s;
System.out.println(f + " - " + s + " = " + result);
}
public void multiplication (int f, int s) {
System.out.println("multiplication()");
int result = f *s;
System.out.println(f + " * " + s + " = " + result);
}
public void division (int f, int s) {
System.out.println("division()");
int result = f /s;
System.out.println(f + " / " + s + " = " + result);
}
}
MyCalculator.java
package DI01;
public class MyCalculator {
Calculator calculator ;
private int firstNum;
private int secondNum;
public MyCalculator() {
}
public void add() {
calculator.addition(firstNum, secondNum);
}
public void sub() {
calculator.substraction(firstNum, secondNum);
}
public void mul() {
calculator.multiplication(firstNum,secondNum);
}
public void div() {
calculator.division(firstNum, secondNum);
}
//setter만 해줌
public void setCalculator(Calculator calculator) {
this.calculator = calculator;
}
public void setFirstNum(int firstNum) {
this.firstNum = firstNum;
}
public void setSecondNum(int secondNum) {
this.secondNum = secondNum;
}
}
MainClass01.java
package DI01;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass01 {
public static void main(String[] args) {
String configLocation = "classpath:applicationCTX01.xml";
AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
MyCalculator myCalculator = ctx.getBean("myCalculator",MyCalculator.class );
myCalculator.add();
myCalculator.sub();
myCalculator.mul();
myCalculator.div();
}
}
Generic써주면 그위에 classpath 써주면 댐
getbean을 쓰면 클래스명 안가져 와도댐
applicationCTX01.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="calculator" class="DI01.Calculator"></bean>
<bean id="myCalculator" class="DI01.MyCalculator">
<property name="calculator"><ref bean="calculator"></ref></property>
<property name="firstNum" value="20"></property>
<property name="secondNum" value="2"></property>
</bean>
</beans>
설명 -- 이해하기 위해서 기본방식과과 비교 시켜봄 위에랑 밑이랑 똑같은것이다 .
오류메세지 예시
applicationCTX01.xml에 소스가 없다 [DI01.MyCalculator]에 secondNum 메소드가 setter 메소드가 없다는 에러메세지
BMICalculatorjava
package DI02;
public class BMICalculator {
private double lowWeight;
private double normal;
private double overWeight; // 과체중
private double obesity; // 비만
public void bmicalculation(double weight, double height) {
double h = height * 0.01;
double result = weight / (h * h);
System.out.println("BMI 지수 :" + (int) result);
if (result > obesity) {
System.out.println("비만. ");
} else if (result > overWeight) {
System.out.println("과체중.");
} else if (result > normal) {
System.out.println("정상.");
} else {
System.out.println("저체중.");
}
}
public void setLowWeight(double lowWeight) {
this.lowWeight = lowWeight;
}
public void setNormal(double normal) {
this.normal = normal;
}
public void setOverWeight(double overWeight) {
this.overWeight = overWeight;
}
public void setObesity(double obesity) {
this.obesity = obesity;
}
}
MyInfo.java
package DI02;
import java.util.ArrayList;
public class MyInfo {
private String name; //call by value
private double height; //call by value
private double weight; //call by value
private ArrayList<String> hobbys; //call by value
private BMICalculator bmiCalculator; //call by reference
public void bmiCalculator() {
bmiCalculator.bmicalculation(weight, height);
}
public void getInfo() {
System.out.println("이름:" + name);
System.out.println("키:" + height);
System.out.println("몸무게:" + weight);
System.out.println("취미:" + hobbys);
bmiCalculator();
}
}
public void setName(String name) {
this.name = name;
}
public void setHeight(double height) {
this.height = height;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setHobbys(ArrayList<String> hobbys) {
this.hobbys = hobbys;
}
public void setBmiCalculator(BMICalculator bmiCalculator) {
this.bmiCalculator = bmiCalculator;
}
}
MainClass02.java
package DI02;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass02 {
public static void main(String[] args){
String configLocation = "classpath:applicationCTX02.xml";
AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
MyInfo myInfo =ctx.getBean("myInfo", MyInfo.class);
myInfo.getInfo();
ctx.close(); //자원의 낭비 줄여줌 . 꼭 close해주기
}
}
Arraylist에 값을 셋팅할때 값을 넣어주는 방식
private ArrayList<String> hobbys;
//Arraylist에 값을 셋팅할때 값을 넣어주는 방식
<property name= "hobbys">
<list>
<value>바둑</value>
<value>대화</value>
</list>
</property>
applicationCTX02.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="bmiCalculator" class="DI02.BMICalculator">
<property name="lowWeight" value="18.5"></property>
<property name="normal" value="23"></property>
<property name="overWeight" value="25"></property>
<property name="obesity" value="30"></property>
</bean>
<bean id="myInfo" class="DI02.MyInfo">
<property name="name" value="김춘추"></property>
<property name="height" value="170"></property>
<property name="weight" value="72"></property>
<property name="hobbys">
<list>
<value>말타기</value>
<value>활쏘기</value>
</list>
</property> //call by reference로 넘겨줄려면 위에 bean id 선언해준거랑 이름 맞춰줘야함
<property name="bmiCalculator"> <ref bean="bmiCalculator"></ref>
</property>
</bean>
</beans>