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

相关文章
相关标签/搜索