본문 바로가기
Programming/Spring Boot

빈(Bean) 생성

by yoon9i 2024. 7. 2.

6. 빈 생성 방법
- 항상 Application.java 의 패키지와 같거나 서브 패키지로 빈을 작성하자.(*)

1> 명시적으로 생성
- @Configuration + @Bean 이용
==> @Configuration 을 통해서 @Bean으로 지정한 빈을 생성했음.
==> @Bean 은 메서드 레벨만 가능.
    @Configuration 는 클래스 레벨만 가능.

package com.exam;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}
package com.exam.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.exam.dao.DeptDAO;

@Configuration // @Configuration 는 클래스 레벨만 가능.
public class DeptConfiguration {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptConfiguration() {
		logger.info("logger: {}", "DeptConfiguration 생성자");
	}
	
	// 명시적으로 직접생성후 @Bean 어노테이션 달기
	// @Bean 은 메서드에서만 사용가능(클래스 사용불가)
	@Bean
	public DeptDAO createDeptDAO() {
		return new DeptDAO();
	}
}
package com.exam.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// Spring Bean
public class DeptDAO {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptDAO() {
		logger.info("logger: {}", "DeptDAO 생성자");
	}
}
# application.properties
logging.level.org.springframework=info
<?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 
	http://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.7.18</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.exam</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>



2> 다른 패키지로 되어 있는 경우
- 명시적으로 패키지를 알려줘야 됨.

    package com.exam;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication(scanBasePackages={"com.exam2"})
    public class DemoApplication {

      public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
      }

    }

    ==> @SpringBootApplication(scanBasePackages={"com.exam2"}) 사용
        없으면 같은 패키지거나 서브패키지에서만 스캔

package com.exam;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.exam2"})
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}
package com.exam2.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.exam.dao.DeptDAO;

@Configuration // @Configuration 는 클래스 레벨만 가능.
public class DeptConfiguration {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptConfiguration() {
		logger.info("logger: {}", "DeptConfiguration 생성자");
	}
	
	// 명시적으로 직접생성후 @Bean 어노테이션 달기
	// @Bean 은 메서드에서만 사용가능(클래스 사용불가)
	@Bean
	public DeptDAO createDeptDAO() {
		return new DeptDAO();
	}
}
package com.exam.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// Spring Bean
public class DeptDAO {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptDAO() {
		logger.info("logger: {}", "DeptDAO 생성자");
	}
}
# application.properties
logging.level.org.springframework=info
<?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 
	http://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.7.18</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.exam</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>




3> 권장 패키지 구조
https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html
#using.structuring-your-code.locating-the-main-class

  com.exam

    @SpringBootApplication (,,@ComponentScan) // Component == Bean
    Application.java

        xxx(패키지)
          Test.java
          Hello.java
          World.java // 여기까지만 @ComponentScan 가 스캔가능

  com.exam2

        yyy(패키지)

          main.java

package com.exam;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}
package com.exam.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

// Spring Bean
// @Configuration // 생성됨
// @Component // 생성됨
// @Repository // 생성됨
//@Service // 생성됨
@Controller // 생성됨
public class DeptDAO {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptDAO() {
		logger.info("logger: {}", "DeptDAO 생성자");
	}
}
# application.properties
logging.level.org.springframework=info
<?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 
	http://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.7.18</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.exam</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>



  ------------------------------------------------------------------------
  첫번째 작업: @SpringBootApplication 와 같은 패키지거나 서브패키지로 작성한다.
  두번째 작업: 클래스에 어노테이션을 지정한다. 
  (@[Configuration|Component|Repository|Service|Controller|RestController])

  com.exam

    @SpringBootApplication (,,@ComponentScan) // Component == Bean
    Application.java

        xxx(패키지)

          @Configuration (빈으로 생성됨) : @Bean 으로 빈 생성시 빈 정보를 설정하는 빈에서 사용
          Test.java

          @Component (빈으로 생성됨) : 범용적으로 사용
          Hello.java

          @Repository (빈으로 생성됨) : DAO 역할의 빈에서 사용
          World.java

          @Service (빈으로 생성됨) : Service 역할의 빈에서 사용
          World2.java

          @Controller (빈으로 생성됨) , @RestController (빈으로 생성됨.)
          World3.java


  com.exam2

        yyy(패키지)
          @Component (빈으로 생성못함.)
          main.java

package com.exam;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}
package com.exam.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

// Spring Bean
// @Configuration // 생성됨
// @Component // 생성됨
// @Repository // 생성됨
//@Service // 생성됨
// @Controller // 생성됨

@Repository
public class DeptDAO {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptDAO() {
		logger.info("logger: {}", "DeptDAO 생성자");
	}
}
package com.exam.service;

public interface DeptService {

}
package com.exam.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class DeptServiceImpl implements DeptService {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	public DeptServiceImpl() {
		logger.info("logger: {}", "DeptServiceImpl 생성자");
	}
}
# application.properties
logging.level.org.springframework=info
<?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 
	http://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.7.18</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.exam</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

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

빈의 scope  (0) 2024.07.02
생성된 빈 접근방법  (0) 2024.07.02
의존성 설정  (0) 2024.07.02
로깅처리  (0) 2024.07.02
개요  (0) 2024.07.02