코디잉

Spring Bean 생성 본문

Spring

Spring Bean 생성

yong_ღ'ᴗ'ღ 2022. 11. 20. 22:48

🔸  DI: Dependency Injection, 의존성 주입

      ◼ new 키워드로 객체 생성을 직접하지 않고, 객체 생성을 외부에서 대신 수행

       클래스/인터페이스 타입의 멤버 변수만 선언하고, 생성자 구현

 

✔ 객체를 생성하는 방법

1. Spring에 의해 객체(Spring Bean)가 생성될 수 있도록 Annotation 설정

    ex) @RestController/@Controller, @Service

    → Spring Framework가 Component Scan 단계에서 특정 Annotation이 붙은 Class를 직접 객체로 생성해준다.

    → Spring Bean으로 생성해서 직접 관리해준다.

2. 사용할 객체를 멤버 변수와 생성자에 추가

3. 객체 사용

new 키워드를 직접 사용하지 않는다.

 

 

객체를 생성하는 또 다른 방법: @Configuration과 @Bean

    ◼ @Configuration: 설정 정보를 위한 클래스로 활용된다.

    ◼ @Bean: @Configuration 클래스 내 메소드 위에 @Bean을 붙여 Bean 생성 가능

        → 객체를 생성해서 반환한다.

// ex)
@Configuration
public class AppConfig {
	
    @Bean
    public PostService postService() {
    	return new PostService();
        //--> @Bean에 의해 return하는 new PostService() 객체가 Spring Bean이 된다.
        //--> Spring에 의해 생성/관리되는 자바 객체
    }
}

 

🔸 Bean/객체를 생성하는 방법 🔸

  1. @Controller, @RestController, @Service 등 특정 Annotation이 붙은 클래스는 Spring Framework가 직접 객체로 만듦
  2. @Configuration 클래스의 @Bean이 붙은 메서드에서 반환되는 객체
  3. XML 설정

 


 

🔥 @Service와 @Configuration,@Bean 모두 쓰면 어떻게 될까? (같은 이름의 Bean 생성할 때)

// ex)
@Configuration
public class AppConfig {

	@Bean
	public PostService postService() {
		return new PostService();
	}
}

// ↓
// ↓   이렇게 했으면, @Service Annotation 지워줘야 함
// ↓

//@Service(x)
public class PostService {
	public PostDto getPost(Integer id) {
		return new PostDto();
	}
}

     → 모두 써놓으면 에러 발생

         (A bean with that name has already been defined in file ~~~)

         @Service 클래스에서도 bean을 생성하려고 하고, @Configuration 클래스에서도 bean을 생성하려고 하니 충돌 발생

 

     → 해결 방법: 두 개의 Bean 이름을 다르게 해주면 된다. 간단하게 메서드 이름 바꿔도 됨

// ex)
@Configuration
public class AppConfig {

	@Bean
	public PostService postService2() {
		return new PostService();
	}
}

//-------------------------------------------

@Service
public class PostService {
	public PostDto getPost(Integer id) {
		return new PostDto();
	}
}

 

같은 종류의 Bean을 생성하더라도, 이름을 다르게 할 수 있다.

해당 메서드의 이름이 → 생성하는 Bean 의 이름이 된다.

이름이 다르면 여러 개 생성할 수 있지만,

이름이 같으면 충돌 발생한다.

 

➕) @SpringBootApplication 어노테이션은 @Configuration 역할까지 수행한다.

 

'Spring' 카테고리의 다른 글

[Gradle] spring-boot-devtools 추가  (0) 2022.12.09
[Maven] Spring Boot에서 MyBatis, H2 Database 사용 설정  (0) 2022.11.21
@Service  (0) 2022.11.17
주요 HTTP Method  (0) 2022.11.16
JSON  (0) 2022.11.16
Comments