惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News and Events Feed by Topic
N
News | PayPal Newsroom
SecWiki News
SecWiki News
P
Privacy International News Feed
T
Troy Hunt's Blog
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
L
LINUX DO - 热门话题
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Security Latest
Security Latest
AWS News Blog
AWS News Blog
S
Secure Thoughts
W
WeLiveSecurity
H
Heimdal Security Blog
T
Threat Research - Cisco Blogs
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
G
GRAHAM CLULEY
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
Cisco Talos Blog
Cisco Talos Blog
雷峰网
雷峰网
Cloudbric
Cloudbric
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
Latest news
Latest news
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
Docker
Recent Announcements
Recent Announcements
博客园 - 【当耐特】
H
Help Net Security
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
Check Point Blog
博客园 - 叶小钗

博客园 - Rock Wang

Asp.Net Core Web Api基于cookie的安全验证 C#语言新特性(6.0-8.0) C#中Struct和Class的区别 iOS真机调试之免费预配(Free provisioning) iOS真机调试 Java学习笔记(9) Java学习笔记(7) Java学习笔记(6) Java学习笔记(5) Java学习笔记(4) Idea常用功能汇总 Java学习笔记(3) Java学习笔记(2) Java学习笔记(1) 如何开发NPM包 c#抓屏功能在DPI缩放后,截到的图片不完整的问题 支持续传功能的ASP.NET WEB API文件下载服务 ASP.NET MVC 阻止通过Url直接访问服务器上的静态文件 VS2013/VS2015/VS2017通过oschina托管代码
Spring Boot学习笔记(1)
Rock Wang · 2019-06-14 · via 博客园 - Rock Wang

@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("\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实例

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