@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) public class DemoApplication { @Bean public Runnable creatRunnale(){ return () -> { System.out.println("springboot is running"); }; } public static void main(String[] args) { ConfigurableApplicationContext contxt = SpringApplication.run(DemoApplication.class, args); contxt.getBean(Runnable.class).run(); } }
註釋@SpringBootApplication 標誌着該類爲項目入口,由於我引用了hibernateJPA ,因此要加上exclude ,使項目能夠在沒有數據庫的環境下啓動.java
因爲大量項目都會在主要的配置類上添加@Configuration,@EnableAutoConfiguration,@ComponentScan
三個註解。spring
分開解釋@Configuration,@EnableAutoConfiguration,@ComponentScan。數據庫
一、@Configuration:提到@Configuration就要提到他的搭檔@Bean。使用這兩個註解就能夠建立一個簡單的spring配置類,能夠用來替代相應的xml配置文件。springboot
@Configuration的註解類標識這個類能夠使用Spring IoC容器做爲bean定義的來源。@Bean註解告訴Spring,一個帶有@Bean的註解方法將返回一個對象,該對象應該被註冊爲在Spring應用程序上下文中的bean。app
二、@EnableAutoConfiguration:可以自動配置spring的上下文,試圖猜想和配置你想要的bean類,一般會自動根據你的類路徑和你的bean定義自動配置。hibernate
三、@ComponentScan:會自動掃描指定包下的所有標有@Component的類,並註冊成bean,固然包括@Component下的子註解@Service,@Repository,@Controller。code
除了使用 SpringApplication.run(DemoApplication.class, args)來啓動外,還有另一種啓動方式.@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})xml
public class DemoApplication { @Bean public Runnable creatRunnale(){ return () -> { System.out.println("springboot is running"); }; } public static void main(String[] args) { // ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); //動態啓動
//SpringApplication application = new SpringApplication(DemoApplication.class);
//配置source
Set<Object> sets = new HashSet<>();
sets.add(DemoApplication.class); //建立applicationg SpringApplication application = new SpringApplication(); application.setSources(sets); //啓動 ConfigurableApplicationContext context = application.run(args); context.getBean(Runnable.class).run(); context.close(); } }