Spring Boot學習筆記(1)

@SpringBootApplication用於註解Spring啓動類,以下所示html

1 @SpringBootApplication  
2 public class Application {  
3     public static void main(String[] args) {  
4         SpringApplication.run(Application.class, args);  
5     }  
6 } 

這個啓動類帶有@SpringBootApplication標記,而且在啓動類的main方法中調用SpringApplication.run方法。run方法接收兩個參數,第一個參數是帶有@Configuration標記的主配置類的類型(這裏恰好和啓動類同名了,但這不是必須的)java

  

@SpringBootApplication的定義以下spring

 1 @Target({ElementType.TYPE})
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Documented
 4 @Inherited
 5 @SpringBootConfiguration
 6 @EnableAutoConfiguration
 7 @ComponentScan(
 8     excludeFilters = {@Filter(
 9     type = FilterType.CUSTOM,
10     classes = {TypeExcludeFilter.class}
11 ), @Filter(
12     type = FilterType.CUSTOM,
13     classes = {AutoConfigurationExcludeFilter.class}
14 )}
15 )
16 public @interface SpringBootApplication {
17     ...
18 }

由上面能夠看出,應用了@SpringBootApplication就至關於同時應用了@Configuration, @ComponentScan和@EnableAutoConfiguration這三個註解。不過每次要加三個註解比較麻煩,能夠用一個代替app

@Configuration用於代表這個類是一個配置類,Spring能夠從這個類的成員變量或者方法中加載配置信息dom

@ComponentScan 的做用就是根據定義的掃描路徑,把符合掃描規則的類裝配到spring容器中ide

 Spring Boot中的幾個關鍵類:spring-boot

1.SpringApplication:經過建立該類的實例(通常直接調用SpringApplication.run方法),對程序進行高級配置ui

SpringApplication app = new SpringApplication(SpringBootSimpleApplication.class);
        app.setBanner(new Banner() {
            @Override
            public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
                out.print("\n\n\tThis is my own banner!\n\n".toUpperCase());
            }
        });
        app.run(args);
SpringApplication app = new SpringApplication(SpringBootSimple
                Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

2.SpringApplicationBuilder:該類提供可鏈式調用的API用於建立SpringApplication和ApplicationContext實例spa

 

public class SpringBootSimpleApplication {
  public static void main(String[] args) {
    new SpringApplicationBuilder()
    .bannerMode(Banner.Mode.OFF)
    .sources(SpringBootSimpleApplication.class)
    .run(args);
  }
}

 

CommandLineRunner和ApplicationRunnercode

若是想在Spring Boot服務完成啓動以前,執行一些操做(相似Asp.Net中的Application_Start事件),就須要用到CommandLineRunner或者ApplicationRunner這兩個接口

具體用法爲:這兩個接口都有run()方法,你須要在其實現類中重寫run()方法,建立這兩個接口(任意一個便可)類型的bean, Spring Boot會自動檢測到這一類的bean,在啓動完成後,當即調用其run()方法,你能夠在run方法裏作一些相似初始化數據、刪除以前的臨時文件等之類的操做。若是有多個這樣的Bean須要在啓動時執行,能夠用@Order來標明執行的順序

這兩個接口的區別是run()接收的參數類型不一樣:CommandLineRunner.run(String...args)   ApplicationRunner.run(ApplicationArguments arg0)

使用方法以下:

CommandLineRunner:

//方式一
@Component
public class CommandLineRunnerBead implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        String strArgs = Arrays.stream(args).collect(Collectors.joining("|"));
        log.info("Application starts with arguments:"+strArgs);
    }
}

//方式2
@Bean
CommandLineRunner runJustBeforeStartup() {
    return args -> {
        String strArgs = Arrays.stream(args).collect(Collectors.joining("|"));
        log.info("Application starts with arguments:"+strArgs);
    };
}

ApplicationRunner:

//方式一
@Component
public class ApplicationRunnerBead implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String strArgs = Arrays.stream(args.getSourceArgs()).collect(Collectors.joining("|"));
        log.info("Application starts with arguments:" + strArgs);
    }
}

//方式二
@Bean
ApplicationRunner runJustBeforeStartup() {
    return args -> {
        String strArgs = Arrays.stream(args.getSourceArgs()).collect(Collectors.joining("|"));
        log.info("Application starts with arguments:" + strArgs);
    };
}

@Autowired:用於修飾成員變量,從容器中查找類型匹配的Bean,而後把這個Bean賦值給被修飾的變量,若是有多個類型匹配的Bean,容器會按名稱進行匹配,即註冊Bean時會指定一個名稱(也可不指定名稱,默認應該是類的名字,沒有了解)

@Bean用於修飾一個方法,這個方法會返回一個對象,Spring把這個對象註冊爲容器中的一個Bean

@Component用於修飾一個類的定義,Spring會建立一個這個類的實例,把這個實例對象註冊爲容器中的一個Bean

@Component@Bean的區別是:@Component是純聲明式的,不能添加任何產生Bean的邏輯,而且只能是本身寫的類;而@Bean是經過方法生成一個Bean,能夠添加生成Bean的邏輯(例如根據不一樣的條件生成不一樣的Bean),而且@Bean能夠做用於第三方類

 

配置應用程序屬性:

經常使用應用程序屬性列表:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

配置文件一般爲application.properties或者application.yml, 放在程序根目錄下

可能經過@Value註解獲取這些屬性值,好比rc/main/resources/application.properties文件中有以下配置項

data.server=remoteserver:3030

可經過以下代碼獲取該配置值

//...
@Service
public class MyService { @Value("${data.server}") private String server; //... }

 Spring Boot查找應用程序配置屬性的優先級順序:

• Command-line arguments
• SPRING_APPLICATION_JSON
• JNDI (java:comp/env)
• System.getProperties()
• OS Environment variables
• RandomValuePropertySource (random.*)
• Profile-specific (application-{profile}.jar) outside of the package jar.
• Profile-specific (application-{profile}.jar) inside of the package jar.

• Application properties (application.properties) outside of the package jar.• Application properties (application.properties) inside of the package jar.• @PropertySource• SpringApplication.setDefaultProperties

相關文章
相關標籤/搜索