Programing

Spring 주석 @Controller는 @Service와 동일합니까?

lottogame 2020. 11. 1. 17:14
반응형

Spring 주석 @Controller는 @Service와 동일합니까?


Spring 주석은 다음 @Controller과 동일 @Service합니까?

비즈니스 논리 @ControllerURL매핑하고 호출하는 데 사용할 수있는 방법 에 대해 알고 있습니다 .

@Service비즈니스 로직을 포함하는 서비스 클래스에 주석을 추가 하는 데 사용됩니다.

서비스 클래스에 주석을 추가 하는 @Controller대신 사용할 수 있습니까 @Service?


아니요, 그들은 서로 상당히 다릅니다.

둘 다 @Component 주석 의 다른 전문화 (실제로는 동일한 인터페이스의 두 가지 다른 구현 임)이므로 둘 다 클래스 경로 스캔에서 발견 할 수 있습니다 (XML 구성에서 선언 한 경우).

@Service 주석은 서비스 계층에서 사용되며 서비스 작업을 수행하는 클래스에 주석을 추가합니다. 종종 사용하지 않지만 대부분의 경우이 주석을 사용하여 모범 사례를 나타냅니다. 예를 들어, DAO 클래스를 직접 호출하여 데이터베이스에 개체를 유지할 수 있지만 이것은 끔찍합니다. DAO를 호출하는 서비스 클래스를 호출하는 것이 좋습니다. 이것은 관심 패턴의 분리를 수행하는 좋은 것입니다.

@Controller 주석은 Spring MVC 프레임 워크 (웹 애플리케이션 구현에 사용되는 Spring Framework의 구성 요소)에서 사용되는 주석입니다. @Controller 주석은 특정 클래스가 컨트롤러 역할을 수행함을 나타냅니다. @Controller 어노테이션은 어노테이션이있는 클래스의 스테레오 타입으로 작동하여 역할을 표시합니다. 디스패처는 매핑 된 메서드에 대해 이러한 주석이 달린 클래스를 스캔하고 @RequestMapping 주석을 감지합니다.

따라서 Spring MVC 아키텍처를 살펴보면 모든 HTTP 요청을 적절한 컨트롤러 클래스 (@Controller로 주석 처리)로 전달하는 프런트 컨트롤러를 나타내는 DispatcherServlet 클래스 (XML 구성에서 선언)가 있습니다. 이 클래스는 해당 메서드에 의해 비즈니스 논리를 수행하고 서비스를 호출 할 수 있습니다. 이러한 클래스 (또는 해당 메서드)는 일반적으로 컨트롤러 및 해당 메서드에 의해 처리되는 HTTP 요청을 지정하는 @RequestMapping 주석 으로 주석 처리됩니다.

예를 들면 :

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private final AppointmentBook appointmentBook;

    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

이 클래스는 컨트롤러입니다.

이 클래스는 "/ appointments" "folder"에 대한 모든 HTTP 요청을 처리하며 특히 get 메서드는 "/ appointments"폴더에 대한 모든 GET HTTP 요청을 처리하기 위해 호출되는 메서드입니다.

이제 더 명확 해 지길 바랍니다.


@Controller, @Service주석 의 정의를 살펴보면 특수한 유형의 @Component주석 임을 알 수 있습니다 .

@Component
public @interface Service {
    ….
}

 

@Component
public @interface Controller {
}

그렇다면 차이점은 무엇입니까?

@제어 장치

@Controller주석은 특정 클래스가 컨트롤러의 역할을 역할을 나타냅니다. @Controller주석은 역할을 나타내는 주석 클래스에 대한 스테레오 타입 역할을합니다.

@Controller의 특별한 점은 무엇입니까?

당신처럼 다른과이 주석을 전환 할 수 없습니다 @Service또는 @Repository그들이 동일하게 표시에도 불구하고. 디스패처 @Controller@RequestMapping주석이 달린 클래스를 스캔하고 그 안의 주석을 감지 합니다. 만 사용할 수 있습니다 @RequestMapping@Controller주석 클래스.


@서비스

@Services 저장소 계층에 비즈니스 로직 및 호출 방법을 보유합니다.

@Service의 특별한 점은 무엇입니까?

그것이 비즈니스 로직을 보유하고 있음을 나타내는 데 사용된다는 사실 외에도이 주석이 제공하는 눈에 띄는 전문성은 없지만 누가 알겠습니까? 스프링은 미래에 추가 예외를 추가 할 수 있습니다.

연결된 답변 : Spring에서 @Component, @Repository 및 @Service 주석의 차이점은 무엇입니까?


아니요, @Controller과 같지는 @Service않지만 둘 다의 전문화이므로 둘 다 @Component클래스 경로 스캔에 의한 검색 후보가됩니다. @Service주석은 서비스 계층에서 사용되며, @Controller프리젠 테이션 계층에서 스프링 MVC 컨트롤러입니다. A는 @Controller일반적으로 URL 매핑을 가질 것이며, 웹 요청에 의해 트리거 될 수있다.


@Service 대 @Controller

@Service : 클래스는 "비즈니스 서비스 외관"(핵심 J2EE 패턴 의미에서) 또는 이와 유사한 것입니다.

@Controller : 주석이 달린 클래스가 "Controller"(예 : 웹 컨트롤러)임을 나타냅니다.

---------- 주요 스테레오 타입에 대한 유용한 정보 찾기 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html

@interface 구성 요소

  @Target(value=TYPE)
     @Retention(value=RUNTIME)
     @Documented
    public @interface Component

주석이 달린 클래스가 구성 요소임을 나타냅니다. 이러한 클래스는 주석 기반 구성 및 클래스 경로 스캔을 사용할 때 자동 감지 후보로 간주됩니다.

다른 클래스 수준 주석도 구성 요소를 식별하는 것으로 간주 될 수 있습니다. 일반적으로 특수한 종류의 구성 요소 : 예 : @Repository 주석 또는 AspectJ의 @Aspect 주석.

@ 인터페이스 컨트롤러

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Controller

Indicates that an annotated class is a "Controller" (e.g. a web controller).

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

@interface Service

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Service

Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state." May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

@interface Repository

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Repository

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects". Teams implementing traditional J2EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.


I already answered similar question on here Here is the Link

No both are different.

@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.

@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.


No you can't they are different. When the app was deployed your controller mappings would be borked for example.

Why do you want to anyway, a controller is not a service, and vice versa.


From Spring In Action

As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.

In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.

참고URL : https://stackoverflow.com/questions/15922991/is-spring-annotation-controller-same-as-service

반응형