Spring/Spring

23-03-16 Spring

모건이삼촌 2023. 3. 16. 14:32

1. jdk 1.8 버전 설치

2. sts 설치

3. tomcat 설치 및 연동

4. 데이터베이스 설치 및 설정

5. 

 

1.1 스프링 레거시 프로젝트 생성

콘피그 템플릿 클릭

 

디폴트빼고 모두 삭제

주로 3뎁스 사용

생성시 프로젝트에서 피를 흘리고 있는데 백그라운드에서 계속 뭔가를 다운받고 잇따는것

 

 

porm.xml 수정

꼭 서버를 끄고 해야된다.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.chanyongyang</groupId>
	<artifactId>controller</artifactId>
	<name>springmvc</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.0.7.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
</project>

spring 관련 버전이 업데이트 된다. 

 

 * 버전업데이트가 안되고 servlet-context에 에러가 날 때 해결방법

C:\Users\사용자명\.m2\repository\org 폴더 내에 springfreamework 폴더를 삭제하고 다시 구동

force update of snapshots/releases를 체크하고 ,ok하면 된다

만약 위 방법으로 해도 안될시

porm.xml의 스프링 프레임워크 버전을 하나 올리던 내리던 해서 어떻게든 해결해야된다.

 

자바 버전 변경

pom.xml의 plugin쪽으로 이동 

기존에는 프로젝트 생성시 1.6 버전으로 되어있다.

1.8로 변경해야함

위를 아래로 변경

 

프로젝트 선택후 알트 f5를 눌러서 업데이트를 하게되면 자바버전이 올라가게 된다.

 

 

롬복 등록

이제 라이브러리 파일이 아닌 태그형태로 가져올 수 있다.

https://mvnrepository.com/artifact/org.projectlombok/lombok/1.18.24

 

 

적절한곳에 붙여넣기 하면 된다

 

※ 스프링의 특징과 의존성 주입

 - 스프링워크를 이용해서 '의존성 주입'에 대한 이해와 테스트

 - 스프링에서 xml을 이용하는 객체 관리 방법

 - 스프링의 테스트 환경 구축

 

1. 의존성 주입과 스프링

 1-1 의존성

  의존성이라는것은 하나의 객체가 다른 객체 없이 제대로 된 역할을 할 수 없다는것을 의미

  하나의 객체가 다른 객체의 상태에 따라 영향을 받는것을 의미

 1-2 주입

   

 1-3 Bean 등록방법

package com.chanyongyang.domain;

import lombok.Data;

@Data
public class Member {
	private String id;
	private String pw;
	private String name;
}
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean class="com.chanyongyang.domain.Member" />
</beans>

member.java에 S가 붙으면 bean이 되었따는 뜻이다.

 

Spring test maven 가져오기

https://mvnrepository.com/artifact/org.springframework/spring-test

 

테스트에 domain 패키지, MemberTests 생성

메서드 명 위에 커서를 놓고 컨트롤 f11을 하게되면 테스트가 실행된다.

 

※ 의존성 주입

package com.chanyongyang.domain;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class MemberTests {
	Member member = new Member();
	
	// 의존성 주입 (기본생성 방식은 싱글턴 방식이다)
	// 같은주소 공유
	@Autowired
	Member member2;
	@Autowired
	Member member3;
	@Autowired
	Member member4;
	
	@Test
	public void testMe() { // 반환타입은 반드시 void 파리미터 없어야함
		System.out.println("Hello Test");
	}
	
	
	@Test
	public void testMember() {
		System.out.println(member);
	}
	
	@Test
	public void testMember2() {
		member2.setId("ycy93");
		member2.setName("양찬용");
		System.out.println(member2);
		System.out.println(member3);
		System.out.println(member4 == member2);
		System.out.println(member3 == member2);
		System.out.println(member3 == member);
	}
}

@Autowored는 기본값이 singleton 방식이다 이를 변경하려면 

root-context.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 https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean class="com.chanyongyang.domain.Member" scope="prototype"/>
</beans>

 

리퀘스트와 세션은 web bean에서 사용

싱글톤은 객체를 같은 주소를 바라보게 해주는것이고

프로토타입은 서로 다른 주소를 보게 하는것

 

더이상 system.out.print를 쓰지않고 로그로 확인하려 한다.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
// logging console창을 안쓸때
@Log4j
public class MemberTests {
	Member member = new Member();
	
	// 의존성 주입 (기본생성 방식은 싱글턴 방식이다)
	// 같은주소 공유
	@Autowired
	Member member2;
	@Autowired
	Member member3;
	@Autowired
	Member member4;
	
	@Test
	public void testMe() { // 반환타입은 반드시 void 파리미터 없어야함
//		System.out.println("Hello Test");
		log.info("Hello Test");
	}

lombok 선언하는곳에 

@Log4j 입력

sysout 사용하려는곳에 log.info() 입력

 

 

* 제어의 역전

IOC (inversion of control)

 

1. 객체를 생성하는 방법

 

1-1 일반적인 객체생성

예) Board board = new Board(); => 결합도가 상당히 높음 

 

1-2 다형성으로 생성

예) BoardService service = new BoardServiceImpl();

 

1-3 디자인 패턴 (생성 패턴)

싱글톤으로 생성

Test test = Test.getInstance();

 

1-4 팩토리

예) getConnection();

 

1-5 빌더패턴예제

package com.chanyongyang.domain;

import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
public class Board {
	private Long bno;
	private String title;
	private String content;
	
	public Board(Long bno, String title, String content) {
		this.bno = bno;
		this.title = title;
		this.content = content;
	}
	public static BoardBuilder builder() {
		return new BoardBuilder();
	}
	public static class BoardBuilder {
		private Long bno;
		private String title;
		private String content;

		public BoardBuilder bno(Long bno) {
			this.bno = bno;
			return this;
		}
		public BoardBuilder title(String title) {
			this.title = title;
			return this;
		}
		public BoardBuilder content(String content) {
			this.content = content;
			return this;
		}
		public Board build() {
			return new Board(bno, title, content);
		}
	}
	
	public static void main(String[] args) {
//		Board board = new Board();
//		Board board = Board.builder().bno(1L).content("abcd").build();
		Board board = Board.builder().bno(1L).title("aaa").title("bbb").content("abcd").build();
		
		System.out.println(board);
				
	}

}

 

DL : 의존성 탐색

DI : 의존성 주입

 

* Java freamwork

ejb,struts , spring

 

 

패키지탐색을 통해서 나중에 이 클래스를 Bean으로 만들어 달라는것

 

 

 

스프링 컨테이너가 후보가 될만한 bean을 찾으러 다니는데 그 빈이 2개이상이면

 

 

★ bean을 주입한다는것 꼭 복습해야함 (이제 new 객체생성을 안할것)

  - 대부분 bean으로 등록되어 스프링의 관리를 받게된다.

 

 

 

 

Spring 에서 맵핑하는법

package com.chanyongyang.controller;

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

import lombok.extern.log4j.Log4j;

@Controller
@Log4j
public class HelloController {
	@GetMapping("hello")
	public void hello(String str) {
		log.warn(str);
	}
	@GetMapping("bye")
	public void bye(String str) {
		log.warn(str);
	}
}

http://localhost/controller/bye?str=1234 이런식으로 파라미터를 직접 입력할 수 도 있다.

 

프로젝트와 jdbc 연결

https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client/2.7.3

pom에 추가

 

※ JDBC 테스트 코드

JDBCTests 클래스 생성

package com.chanyongyang.persistence;

import java.sql.Connection;
import java.sql.DriverManager;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class JDBCTests {
	@Test
	public void testConnection() {
		try(Connection conn = DriverManager.getConnection
				("링크", "계정명", "비밀번홍")) {
			log.info(conn);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
	}
}

 

※ 커넥션풀 설정

 - 

https://mvnrepository.com/artifact/com.zaxxer/HikariCP/4.0.3

hikaricp pom에 추가

root-context.xml에 hikari 관련 구문 추가

 

※ mybatis

1. 라이브러리 추가

 1-1 mybatis

https://mvnrepository.com/artifact/org.mybatis/mybatis/3.5.6

 1-2 mabatis-Spring

https://mvnrepository.com/artifact/org.mybatis/mybatis-spring/1.3.2

 1-3  tx, jdbc

	<dependency>
   		 <groupId>org.springframework</groupId>
   		 <artifactId>spring-tx</artifactId>
   		 <version>${org.springframework-version}</version>	
	</dependency>
		<dependency>
   		 <groupId>org.springframework</groupId>
   		 <artifactId>spring-jdbc</artifactId>
   		 <version>${org.springframework-version}</version>	
	</dependency>

 총 4개의 라이브러리 pom.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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://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">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean class="com.chanyongyang.domain.Member" scope="prototype"/>
	
	<context:component-scan base-package="com.chanyongyang.domain" />
	<mybatis-spring:scan base-package="com.chanyongyang.mapper"/>
	<bean class="com.zaxxer.hikari.HikariConfig" id="hikariConfig">
		<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
		<property name="jdbcUrl" value="dbconn" />
		<property name="username" value="id" />
		<property name="password" value="pw" />
	</bean>
	
	<bean class="com.zaxxer.hikari.HikariDataSource" destroy-method="close" id="dataSource">
		<constructor-arg ref="hikariConfig" />
	</bean>
	
	<bean class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
	</bean>
		
</beans>

 

1-4 root-context.xml Namespaces에 mybatis 체크

 

1-5. main 패키지에 mapper 패키지 추가 => TimeMapper 인터페이스 생성

package com.chanyongyang.mapper;

import java.util.Date;

import org.apache.ibatis.annotations.Select;

public interface TimeMapper {
	@Select("select now()")
	public Date getTime();
}

 

1-6 test 패키지에 mapper 패키지 추가 => TimeMapperTests 클래스 생성

package com.chanyongyang.mapper;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class TimeMapperTests {
	@Autowired
	private TimeMapper timeMapper;
	
	@Test
	public void testGetTime() {
		log.info(timeMapper.getTime());
	}

}

 

'Spring > Spring' 카테고리의 다른 글

23-03-29 Spring  (0) 2023.03.30
23-03-23 Spring  (0) 2023.03.23
23-03-22 Spring  (0) 2023.03.22
23-03-21 Spring 비밀글  (0) 2023.03.21
23-03-17 Spring  (0) 2023.03.17