Spring Boot

Spring Boot 기본 설정

0304호 2023. 2. 10.

처음에 Spring Boot 프로젝트를 생성하면 

데이터베이스연결과 커넥션풀 연결을 자동으로 처리해주는 application.properties에 아래 코드처럼 설정해준다

server.port=포트번호(숫자 4자리)

#############데이터베이스 연결, 커넥션풀 자동연결##############
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:"포트번호"/spring?serverTimezone=Asia/Seoul
spring.datasource.username="아이디"
spring.datasource.password="비밀번호"

타임리프 뷰를 사용하기 위해선  Build_gradle에 모듈을 추가한다.

	//타임리브 뷰를 사용하려면
	// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

Spring Boot에서 개별적인 Bean을 설정하면 Application Context를 사용해서 확인한다.

 

@Configuration		//개별적인 스프링 빈 설정 파일
public class WebConfig implements WebMvcConfigurer{

	//빈을 보관하고 있는 장소(스프링 컨테이너)
	@Autowired
	ApplicationContext applicationContext;

	//application.properties에 선언된 변수를 바로 참조
	@Value("${server.port}")
	String port;
	
	@Bean		//해당 메서드를 실행하게됨
	public void test() {
		//bean
		TestBean t = applicationContext.getBean(TestBean.class);
		System.out.println(t);
		
		int c = applicationContext.getBeanDefinitionCount();
		System.out.println("빈의 개수 : " + c);
		
		System.out.println("properties에 선언된 port의 값 : "+port);
	}
	
	@Bean
	public TestBean testBean() {
		System.out.println("테스트 빈 2 실행됨~~~~");
		return new TestBean();		//빈으로 등록
	}	
}

Builder패턴 - 디자인패턴

빌더 패턴의 모형 - 내부 클래스를 생성하고, 외부에서 호출시 내부 클래스의 값을 지정하는형태
장점 - 객체의 불변성 (값의 변경을 막고, 사용시 가독성이 좋음)

 

package com.simple.basic.command;

public class BuilderVO {
	//빌더 패턴의 모형	-	내부 클래스를 생성하고, 외부에서 호출시 내부 클래스의 값을 지정하는형태
	//장점 - 객체의 불변성 (값의 변경을 막고, 사용시 가독성이 좋음)
	
	//1. 멤버변수
	private String name;
	private int age;
	
	//4. VO의 생성자
	public BuilderVO(Builder builder) {
		this.name = builder.name;
		this.age = builder.age;
	}
	
	//7. 외부에서 객체생성을 요구하면 내부에 있는 Builder 클래스를 반환
	public static Builder builder() {
		return new Builder();
	}
	
	//8. toString 오버라이딩
	@Override
	public String toString() {
		return "BuilderVO [name=" + name + ", age=" + age + "]";
	}

	//2. 내부클래스 생성 - 클래스안에클래스
	public static class Builder {
		private String name;
		private int age;
		
		//3. 생성자 제한
		public Builder() {
			// TODO Auto-generated constructor stub
		}
		
		//5. 내부 클래스에 setter메서드 생성
		public Builder setName(String name) {
			this.name = name;
			return this;
		}
		public Builder setAge(int age) {
			this.age = age;
			return this;
		}
		
		//6. build메서드를 생성 - 나 자신을 외부클래스에 저장하고 반환
		public BuilderVO build() {
			return new BuilderVO(this);
		}		
	}	
}

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

Spring Boot DB (MyBatis)  (0) 2023.02.14
Spring Boot Valiadation  (0) 2023.02.14
Thymeleaf in Spring Boot  (0) 2023.02.13
Spring Boot Lombok으로 Builder패턴 만들기  (0) 2023.02.13
SpringBoot 생성  (0) 2023.02.10

댓글