spring boot是基于spring 开发的,因此,spring boot工程中可以使用spring 的注解。除了spring注解外,spring boot会使用到的注解有:
@SpringBootApplication
@Configuration
@Bean
@ComponentScan
@EnableAutoConfiguration
1.@ComponentScan:
扫描指定包下的@Controller,@Service,@Repository,@Component注解,并将被这些注解注释的类纳入到spring容器中管理。默认情况下,扫描的包为当前类所在的包及其子包
指定扫描包的方式:
1)指定一个包:@ComponentScan("com.spirngboot.package")
2)指定多个包:@ComponentScan({"com.springboot.package1","com.springboot.package2"})
如:
@ComponentScan({"com.aaa","com.liuxuelin"}) //这个注解表示将会扫描com.aaa和com.liuxuelin两个包及其子包下的注解
@SpringBootApplication //默认情况下,如果不加上面的注解,扫描的是这个启动类( Application )所在的包及其子包的注解
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.@Configuration和@Bean
@Configuration加在类上,声明当前类是一个配置类,相当于一个Spring的XML配置文件,可以将这个注解看成是spring配置文件中的<beans>标签。
@Bean和@Configuration配合使用,加在方法上,相当于spring 配置文件中的<bean>,加上这个注解后,会将这个方法返回的对象交给spring 容器管理。
如:
@Configuration //申明这个类为配置类,相当于<beans>
public class BeanConf {
@Bean //相当于<bean>,会将这个方法返回的Car对象交给spring 管理
public Car getCar(){
return new Car("宝马",2000000.0);
}
... ... //可配置多个
}
3.@EnableAutoConfiguration
1.@SpringBootApplication
相当于三个注解:@ComponentScan、@Configuration和@EnableAutoConfiguration注解。