spring 机制 扫描包
控制器示例
扫描包注解代码
@SpringBootApplication(scanBasePackages = {"cn.maxhou.*"})
引号内为包名,支持*通配符
为什么要扫描包?
spring 机制,被spring 扫描后,才可能被实例化(被实例化才被调用)
如果使用@Controller和@EnableAutoConfiguration 注解还应该再加上一个注解:@ComponentScan 就可以了。@Controller和@EnableAutoConfiguration没有扫描注解的功能,而@ComponentScan是
springboot专门用来扫描@Component, @Service, @Repository, @Controller等注解的注解
总结:
使用springboot启动类配置扫描的两种注解配置方式:
1、@Controller
@EnableAutoConfiguration
@ComponentScan
2、@SpringBootApplication
@SpringBootApplication注解等价于@Configuration, @EnableAutoConfiguration and @ComponentScan
另外application.java(启动类)也应该按照官方的建议放在root目录下,这样才能扫描到Service和dao,不然还会引起,扫描不到注解的问题。
--- 更新日期:2018-10-14 ---
最近用了最新的springboot 2.0.5.RELEASE 版本 多了一种新的扫描注解,新版的springboot application可以放在任意位置,只要加上
@ComponentScan(basePackages = {"com.oskyhang", "com.frames"})
注解就可以,注解指定扫描的包,就可以扫描到,更灵活方便。
来源:https://www.cnblogs.com/oskyhg/p/6683629.html