Annotated a class with @Configuration and @Controller. Need help in refactoring

前端 未结 6 615
一整个雨季
一整个雨季 2021-01-17 15:49

Below is my class in which i had to use both @Configuration and @Controller as there should be only one instance of Thymeleaf in the e

6条回答
  •  爱一瞬间的悲伤
    2021-01-17 16:20

    If you see the source codes of the annotations (Spring 5) you have:

    Controller

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Controller {
    
        /**
         * The value may indicate a suggestion for a logical component name,
         * to be turned into a Spring bean in case of an autodetected component.
         * @return the suggested component name, if any (or empty String otherwise)
         */
        @AliasFor(annotation = Component.class)
        String value() default "";
    
    }
    

    Configuration

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Configuration {
    
        /**
         * Explicitly specify the name of the Spring bean definition associated
         * with this Configuration class. If left unspecified (the common case),
         * a bean name will be automatically generated.
         * 

    The custom name applies only if the Configuration class is picked up via * component scanning or supplied directly to a {@link AnnotationConfigApplicationContext}. * If the Configuration class is registered as a traditional XML bean definition, * the name/id of the bean element will take precedence. * @return the suggested component name, if any (or empty String otherwise) * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator */ @AliasFor(annotation = Component.class) String value() default ""; }

    you notice that they are the same (they both include the more generic @Component annotation). So it doesn't make sense to use them both by seeing this fact. Another thing, more important, is that spring is trying to give a sort of tags meaning of these annotations that should describe the use.

    The Configuration is used to wire in necessary parts to the application to function properly, at startup phase.

    The Controller is used to define a class which is serving as an interface to the outside world, i.e: how can other actors use your application.

    As you can see, it makes very little sense to use those 2 together.

提交回复
热议问题