Spring 01 (23.04.06)

Jane·2023년 4월 6일
0

IT 수업 정리

목록 보기
99/124

1. 특징

  • Java의 프레임워크
  • 정형화, 일정 수준의 품질 이상, 유연성, 유지보수가 쉽다
  • 무겁다, 습득 시간이 오래 걸린다

2. 프로젝트 만들기

2-1. 프로젝트 Import

  • Package Explorer > Import

  • Projects, Copy projects

2-2. 계산기 예제

  • /src/main/java
    • Calculator.java : 일반적인 더하기, 빼기, 곱하기, 나누기 함수
    • MyCalculator.java : Calculator 함수를 받아서 호출
    • MainClass.java : 프로그램 실행
      (MyCalculator 객체 생성 후 설정한 뒤 함수 실행)

[Console]
addition()
10 + 2 = 12
subtraction()
10 - 2 = 8
multiplication()
10 * 2 = 20
division()
10 / 2 = 5

  • 2번 예제 Main Class
package com.javalec.ex;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		
		/*
		MyCalculator myCalculator = new MyCalculator();
		myCalculator.setCalculator(new Calculator());
		
		myCalculator.setFirstNum(10);
		myCalculator.setSecondNum(2);
		
		myCalculator.add();
		myCalculator.sub();
		myCalculator.mul();
		myCalculator.div();
		*/
		
		String configLocation = "classpath:applicationCTX.xml";
		AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
		MyCalculator myCalculator = ctx.getBean("myCalculator", MyCalculator.class);
		
		myCalculator.add();
		myCalculator.sub();
		myCalculator.mul();
		myCalculator.div();
		
	}
	
}
  • src/main/resources > applicationCTX.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="com.javalec.ex.Calculator" />
	
	<bean id="myCalculator" class="com.javalec.ex.MyCalculator">
		<property name="calculator">
			<ref bean="calculator"/>
		</property>
		<property name="firstNum" value="10" />
		<property name="secondNum" value="2"></property>
	</bean>

</beans>

3. 실습

3-1. 연필 만들기

Pencil.java

package com.javalec.ex;

public interface Pencil {
	public void use();
}

Pencil4B.java

package com.javalec.ex;

public class Pencil4B implements Pencil {

	@Override
	public void use() {
		// TODO Auto-generated method stub
		System.out.println("4B Pencil");
	}
	
}

Pencil6B.java

package com.javalec.ex;

public class Pencil6B implements Pencil {

	@Override
	public void use() {
		// TODO Auto-generated method stub
		System.out.println("6B Pencil");
	}
	
}

Pencil6BWithEraser.java

package com.javalec.ex;

public class Pencil6BWithEraser implements Pencil {

	@Override
	public void use() {
		// TODO Auto-generated method stub
		System.out.println("6B Pencil with Eraser");
	}
	
}

resource > applicationCTX2.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">

<!-- com.javalec.ex.Pencil4B pencil = new com.javalec.ex.Pencil4B -->
	<bean id="pencil" class="com.javalec.ex.Pencil4B"></bean>

</beans>

Mainclass.java

package com.javalec.ex;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		
		String configLocation = "classpath:applicationCTX2.xml";
		AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
		Pencil pencil = ctx.getBean("pencil", Pencil.class);
		pencil.use();
		
	}
	
}

4. Spring MVC

4-1. 프로젝트 생성

  • New > Spring Starter Project


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v2.7.10)

2023-04-06 12:59:54.699  INFO 9896 --- [           main] e.g.ex.SpringBootJyHelloApplication      : Starting SpringBootJyHelloApplication using Java 11.0.17 on DESKTOP-VQTNF27 with PID 9896 (C:\Users\USER\Documents\workspace-sts-3.9.11.RELEASE\spring_boot_jy_hello\target\classes started by USER in C:\Users\USER\Documents\workspace-sts-3.9.11.RELEASE\spring_boot_jy_hello)
2023-04-06 12:59:54.702  INFO 9896 --- [           main] e.g.ex.SpringBootJyHelloApplication      : No active profile set, falling back to 1 default profile: "default"
2023-04-06 12:59:55.477  INFO 9896 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-04-06 12:59:55.477  INFO 9896 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-04-06 12:59:55.477  INFO 9896 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.73]
2023-04-06 12:59:55.591  INFO 9896 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-04-06 12:59:55.591  INFO 9896 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 837 ms
2023-04-06 12:59:55.910  WARN 9896 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.PortInUseException: Port 8080 is already in use
2023-04-06 12:59:55.917  INFO 9896 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2023-04-06 12:59:55.933  INFO 9896 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-04-06 12:59:55.949 ERROR 9896 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.


src>main>resources - application.properties

#server port number
server.port = 8282
  • 다시 실행하면 새로운 포트 번호를 사용하는 스프링 부트를 실행하게 된다.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v2.7.10)

2023-04-06 13:03:12.083  INFO 9100 --- [           main] e.g.ex.SpringBootJyHelloApplication      : Starting SpringBootJyHelloApplication using Java 11.0.17 on DESKTOP-VQTNF27 with PID 9100 (C:\Users\USER\Documents\workspace-sts-3.9.11.RELEASE\spring_boot_jy_hello\target\classes started by USER in C:\Users\USER\Documents\workspace-sts-3.9.11.RELEASE\spring_boot_jy_hello)
2023-04-06 13:03:12.087  INFO 9100 --- [           main] e.g.ex.SpringBootJyHelloApplication      : No active profile set, falling back to 1 default profile: "default"
2023-04-06 13:03:12.861  INFO 9100 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8282 (http)
2023-04-06 13:03:12.876  INFO 9100 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-04-06 13:03:12.876  INFO 9100 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.73]
2023-04-06 13:03:12.970  INFO 9100 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-04-06 13:03:12.970  INFO 9100 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 823 ms
2023-04-06 13:03:13.298  INFO 9100 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8282 (http) with context path ''
2023-04-06 13:03:13.310  INFO 9100 --- [           main] e.g.ex.SpringBootJyHelloApplication      : Started SpringBootJyHelloApplication in 1.649 seconds (JVM running for 2.548)

4-2. 안녕하세요

  • Spring Boot App을 켜고 'localhost:8282'로 접속

HomeController.java

package edu.global.ex.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
	
	@GetMapping("/")
	public String home() {
		return "Hello";
	}
	
	@GetMapping("/hello")
	public String hello() {
		return "Hello World";
	}
}

4-3. pom.xml


  • 버전을 2.6.3으로 바꾼다.
  • 라이브러리 Dependency

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.3</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>edu.global</groupId>
	<artifactId>ex</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring_boot_jy_hello</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>

	<repositories>
      <repository>
         <id>oracle</id>
         <url>http://www.datanucleus.org/downloads/maven2/</url>
      </repository>
   </repositories>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <!-- spring-boot-devtools는 클래스 수정시 웹서버를 재시작하여 결과를 바로 반영 -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-tomcat</artifactId>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <!-- 오라클 JDBC 드라이버 -->
      <dependency>
          <groupId>oracle</groupId>
          <artifactId>ojdbc6</artifactId>
          <version>11.2.0.3</version>
      </dependency>

      <!-- MyBatis 라이브러리 -->
      <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>2.1.4</version>
      </dependency>

      <!-- MyBatis sql pretty -->
      <dependency>
         <groupId>org.bgee.log4jdbc-log4j2</groupId>
         <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
         <version>1.16</version>
      </dependency>

      <!-- JSP를 사용하기 위한 라이브러리 -->
      <!-- 톰캣 파서 -->
      <dependency>
         <groupId>org.apache.tomcat.embed</groupId>
         <artifactId>tomcat-embed-jasper</artifactId>
      </dependency>

      <!-- jstl 라이브러리 -->
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
               <url>http://146.56.137.240:8282/manager/text</url>
               <username>admin</username>
               <password>1234</password>
            </configuration>
         </plugin>
         <!-- cmd에 입력 ( 배포 ) : mvnw.cmd tomcat7:redeploy -->
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

	
</project>

4-4. application.properties

#server port number
server.port = 8282

#datasource (oracle)
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
#spring.datasource.driver-class-name=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
#spring.datasource.url=jdbc:log4jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=scott
spring.datasource.password=tiger


#xml location
mybatis.mapper-locations=classpath:mappers/**/*.xml

#### jsp 
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

4-5. lombok

  • https://projectlombok.org/download

  • 이클립스가 설치되어 있는 폴더에 lombok.jar 을 넣는다.
    폴더 경로 예시 :: [C:\eclipse\spring-tool-suite-3.9.11.RELEASE-e4.14.0-win32-x86_64\sts-bundle\sts-3.9.11.RELEASE]

  • lombok.jar를 누르면 고추 화면이 나온다.

  • Specify Location > 폴더 경로 > STS.exe 찾아서 Select

  • Install / Update 하여 설치

  • Install Successful을 확인하면 Quit Installer

profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글