Spring Boot学习笔记(1)

@SpringBootApplication用于注解Spring启动类,如下所示

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标记的主配置类的类型(这里刚好和启动类同名了,但这不是必须的)

  

@SpringBootApplication的定义如下

 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这三个注解。不过每次要加三个注解比较麻烦,可以用一个代替

@Configuration用于表明这个类是一个配置类,Spring可以从这个类的成员变量或者方法中加载配置信息

@ComponentScan 的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中

 Spring Boot中的几个关键类:

1.SpringApplication:通过创建该类的实例(一般直接调用SpringApplication.run方法),对程序进行高级配置

SpringApplication app = new SpringApplication(SpringBootSimpleApplication.class);
        app.setBanner(new Banner() {
            @Override
            public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
                out.print("

	This is my own banner!

".toUpperCase());
            }
        });
        app.run(args);
SpringApplication app = new SpringApplication(SpringBootSimple
                Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

2.SpringApplicationBuilder:该类提供可链式调用的API用于创建SpringApplication和ApplicationContext实例

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

CommandLineRunner和ApplicationRunner

如果想在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

原文地址:https://www.cnblogs.com/xclw/p/10574085.html