SpringBoot学习笔记(二)
一、Spring Boot核心
1.基本配置
1.1.1入口类和@Spring-BootApplication
其中@Spring-BootApplication注解组合了@Configuration,@EnableAutoConfiguration,@ComponentScan。其中@EnableAutoConfiguration注解可以让SpringBoot项目根据类路径中的jar包依赖为当前项目进行自动配置。
Spring Boot会自动扫描@Spring-BootApplication所在类的同级包以及下级包里的Bean。
1.1.2Spring Boot的配置文件
Spring Boot使用一个全局的配置文件application.yml,放置在src/main/resources目录或者类路径的/config下。
在该配置文件中可以配置服务器端口号以及设置访问路径,例如原来的端口为8080
server:
port: 9090
context-path: /d
更改后的效果如下:
1.1.3常规属性配置
server:
port: 9090
context-path: /d
book:
author: daixaingyu
name: spring boot
在配置文件中配置属性值,然后通过@Value注入即可。代码如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) //Spring Boot项目的核心注解,主要目的是开启自动配置。
public class DatamergeApplication {
@Value("${book.author}")
private String bookAuthor;
@Value("${book.name}")
private String bookName;
@RequestMapping("")
String index(){
return "book name is"+bookName+"and book author is"+bookAuthor;
}
public static void main(String args[]){
SpringApplication.run(DatamergeApplication.class,args);
}
}
运行项目效果为: