SpringBoot控制层中,@Service 替代@Controller
@Service
和@Controller
注解都能被Spring容器所加载,并注入到Spring容器中。我们以SpringBoot应用为例来分析其注入容器的全过程。
对于Spring而言其会根据配置(如 XML 文件或 @ComponentScan
注解)扫描指定的包及其子包,查找标记有 @Controller
、@Service
、@Repository
和 @Component
的类。但对于Springboot应用而言,其并没有显示的使用XmL配置或@ComponentScan
指定扫描路径的方式来加载对应路径下的Bean信息。
这背后的原因主要在于@SpringBootApplication
注解的使用,@SpringBootApplication
其实是一个组合注解,其内部包括以下三个注解:
- @EnableAutoConfiguration: 启用 Spring Boot 的自动配置机制。
- @ComponentScan: 启用组件扫描,以便自动发现并注册 Spring 组件。
- @Configuration: 表示这是一个 Spring 配置类。
在默认情况下,Spring Boot 会从主应用类所在的包开始进行组件扫描,这意味着只要 @Controller
和 @Service
注解的类位于主应用类所在包及其子包中,它们就会被自动发现并注册到 Spring 容器中。
当我们在main方法中执行SpringApplication.run
时,其在run方法内容会完成Spring容器的创建,以及Bean的加载。具体来看,其在AbstractApplicationContext
中的invokeBeanPostBeanFactoryPostProcessore
时,会通过 ConfigurationClassPostProcessor
的 postProcessBeanDefinitionRegistry
方法加载路径下所有的bean名称信息,然后在finshBeanFactoryInitialization
完成bean的实例化。而我们绕了这么一大圈就是皆在说明,被@Service
,@Controller
所标注的类在SpringBoot框架中是如何一步步被注入到容器的。
对于控制层内的方法,其会在AbstractHandlerMethodMapping
中的 afterPropertiesSet()
完成请求url与方法的映射绑定。更进一步,afterPropertiesSet
的处理逻辑全部委托于于 getCandidateBeanNames
和processCandidateBean
两个方法。而getCandidateBeanNames
会获取当前容器中所有的bean 的名称集合,并筛选类中标有@Controller
或者 @RequestMapping
注解的类交给processCandidateBean
处理,以完成请求url与方法的映射。
@Service
@RequestMapping("/ts")
public class ServiceController {
// ....省略内部细节信息
}
不难发现,其虽然没使用@Controller
修饰,但其却被@RequestMapping
注解信息,也就是说其能被processCandidateBean
所处理,进而其也就能完成url和方法映射关系的维护。更进一步,当请求至DispatcherServlet
时,SpringMVC变更通过其url信息,找到能处理相应请求的HandlerMethod
。从而也就能完成url的处理以及视图的渲染。
事实上,只要你能确保Bean信息注入到容器,并且类信息上至少有@Controller
或者 @RequestMapping
注解,那便能在AbstractHandlerMethodMapping
中所解析,然后完成url与方法的绑定!