一哥,CustomBeanConfig类中的@Configuration换成@Service 可以吗?
来源:5-2 【简单好用的SpringBoot】SpringBoot 常用功能特性介绍

qq_多米奇亚_0
2019-02-24
有点不懂业务层中使用的是@service 和有些配置类则使用 @Configuration @bean
1回答
-
同学你好:
你这里提到的这个问题,其实就是 Spring 中使用 @Repository、@Service、@Controller 和 @Component 将类标识为 Bean。下面,我对这几个注解做出说明:Spring 从 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的开发。@Repository 注解便属于最先引入的一批,它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean。Spring 2.5 在 @Repository 的基础上增加了功能类似的额外三个注解:@Component、@Service、@Controller,它们分别用于软件系统的不同层次:
1. @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次;
2. @Service 通常作用在业务层,但是目前该功能与 @Component 相同;
3. @Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。
通过在类上使用 @Repository、@Component、@Service 和 @Constroller 注解,Spring 会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。
最后,我们来看下 @Configuration 注解,它的定义如下:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration { String value() default ""; }
因为 @Configuration 注解本身定义时被 @Component 标注了。因此可以说,一个 @Configuration 同时也是一个 @Component。这个注解是用在配置类上的,我们需要在配置信息的类上加上 @Configuration 注解,以明确指出该类是 Bean 配置的信息源。
综上所述:CustomBeanConfig 类中的 @Configuration 是不可以换成 @Service 的。
欢迎来 QQ 群随时交流、讨论,也非常感谢同学的支持!
322019-04-04
相似问题