之前用戶使用的是3個(gè)注解注解他們的main類。分別是@Configuration,@EnableAutoConfiguration,@ComponentScan。由于這些注解一般都是一起使用,spring boot提供了一個(gè)統(tǒng)一的注解@SpringBootApplication舅世。
@SpringBootApplication = (默認(rèn)屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan屉符。
@SpringBootApplication
public class ApplicationMain {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
分開解釋@Configuration,@EnableAutoConfiguration,@ComponentScan涣易。
- @Configuration:提到@Configuration就要提到他的搭檔@Bean。使用這兩個(gè)注解就可以創(chuàng)建一個(gè)簡單的spring配置類焊刹,可以用來替代相應(yīng)的xml配置文件系任。
@Configuration
public class Conf {
@Bean
public Car car() {
Car car = new Car();
car.setWheel(wheel());
return car;
}
@Bean
public Wheel wheel() {
return new Wheel();
}
}
@Configuration的注解類標(biāo)識這個(gè)類可以使用Spring IoC容器作為bean定義的來源。@Bean注解告訴Spring虐块,一個(gè)帶有@Bean的注解方法將返回一個(gè)對象俩滥,該對象應(yīng)該被注冊為在Spring應(yīng)用程序上下文中的bean。
@EnableAutoConfiguration:能夠自動配置spring的上下文贺奠,試圖猜測和配置你想要的bean類霜旧,通常會自動根據(jù)你的類路徑和你的bean定義自動配置。
@ComponentScan:會自動掃描指定包下的全部標(biāo)有@Component的類儡率,并注冊成bean挂据,當(dāng)然包括@Component下的子注解@Service,@Repository,@Controller。