learn/spring

어노테이션(Annotation) - 컴포넌트 스캔(Component Scan) 관련

사겅이 2023. 9. 21. 04:29

 컴포넌트 스캔(Component Scan) 관련

 

출처 : http://mvpjava.com/component-vs-service-spring/

 

 

자바 코드에 메타데이터를 부여하여 해당 코드의 동작 방식을 정의하거나 특정 기능을 활성화하는 데 사용되는 특별한 주석 형태의 요소. 클래스, 메서드, 필드 등과 같은 다양한 요소에 적용할 수 있으며, 애플리케이션을 설정하고 관리

Annotations are special comment-like elements used in Java code to provide metadata, define the behavior of the code, or activate specific functionalities. They can be applied to various elements such as classes, methods, fields, and more. Annotations are used for configuring and managing applications.

 

@ComponentScan

컴포넌트 스캐닝(Component scanning)을 수행하여 지정된 패키지와 그 하위 패키지서 다른 컴포넌트 관련 어노테이션이 지정된 클래스를 찾아서 Bean으로 등록

@Component

@Controller

@Service

@Repository

@Configuration

 

@Configuration
@ComponentScan(basePackages = {"com.example.myapp", "com.example.other"},
        includeFilters = @ComponentScan.Filter(Controller.class))
public class AppConfig {
    // Configuration code...
}

 

@Component

개발자가 직접 작성한 Class를 Bean으로 등록

Component에 추가 정보가 없다면 Class의 이름을 camelCase로 변경한 것을 Bean id로 사용

@Component("myBean") // Bean의 이름을 "myBean"으로 지정
@Component(value = "mystudent") // Bean의 이름을 "mystudent"로 지정
public class MyComponent {
    // 클래스의 기능 구현
}

 

@Controller

웹 요청을 처리하고 뷰를 반환

API 서비스로 사용하는 경우는 @ResponseBody를 사용하여 객체를 반환

@Controller
public class MyController {
    // View를 사용하는 예제
    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "helloPage"; // "helloPage"는 뷰 이름
    }
    // API를 사용하는 예제
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello, World!";
    }
}

 

@Service

Service Layer의 구성 요소를 표시하며 Service Layer는 비즈니스 로직을 처리하고 중요한 기능을 수행하는 데 주로 사용

@Service
public class MyService {

    public String doSomething() {
        // 비즈니스 로직 수행
        return "Result from MyService";
    }
}

 

@Repository

Data Access Layer의 구성 요소를 표시하며 데이터 Data Access Layer는 주로 데이터베이스와의 상호 작용을 처리하고 데이터의 저장 및 검색을 담당

@Repository
public class UserRepository {

    public User findById(Long userId) {
        // 데이터베이스에서 userId에 해당하는 사용자 정보를 조회하는 로직
        return new User(userId, "John Doe");
    }

    public void save(User user) {
        // 사용자 정보를 데이터베이스에 저장하는 로직
    }
}

 

@Configuration

해당 클래스가 Spring Bean 구성 정보를 포함하고 있음을 나타냄

@Configuration을 클래스에 적용하고 @Bean을 method에 적용하여 @Autowired로 Bean 사용 

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }

    @Bean
    public MyRepository myRepository() {
        return new MyRepository();
    }
}

@Service
public class MyService {

    private final MyRepository myRepository;

    @Autowired
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // 다른 메서드들
}

@Service
public class MyRepository {
    // Repository 내용
}

 

@Transactional

선언적 트랜잭션 관리를 지원하며, 트랜잭션 범위 내에서 메서드 실행을 보장

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public void createUser(User user) {
        // 사용자 생성 로직
        userRepository.save(user);
    }

    @Transactional
    public User getUserById(Long userId) {
        // 사용자 조회 로직
        return userRepository.findById(userId).orElse(null);
    }
}