SpringBoot系列—基础配置

来源:互联网 发布:应用更新软件 编辑:程序博客网 时间:2024/04/30 03:14

入口类

SpringBoot项目一般在项目的根包目录下会有一个artifactId+Application命名规则的入口类,入口类有一个main方法(标注的java应用的的入口方法),main方法中使用SpringApplication.run()启动应用项目。

例:

package com.example.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringBootDemo1Application {   public static void main(String[] args) {      //通过app.set方法可以设定一些启动参数      SpringApplication app = new SpringApplication(SpringBootDemo1Application.class);      app.run();      /**或直接启动       * SpringApplication.run(SpringBootDemo1Application.class, args);       */   }}
@SpringBootApplication是Spring Boot 的核心注解,它是一个组合注解主要目的是为了开启自动配置,其中@EnableAutoConfiguration是为了让Spring Boot根据类路径中jar包依赖为当前项目进行自动配置。Spring Boot会自动扫描@SpringBootApplication所在同级包以及下级包的bean。想关闭特定的自动配置可以使用@SpringBootApplication注解的exclude参数例如:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

配置文件

Spring Boot使用一个全局配置文件application.properties 或 application.yml (yaml语言是以数据为中心的语言,在配置数据的时候具有面向对象的特征)放置在src/main/resources目录下或者类路径的/config下。

例如修改端口和默认访问路径“/”

server:  port: 8082  context-path: /demo

常规属性配置和类型安全配置

配置文件添加

book:  author: xianjj  name: AABB

类型安全的bean

package com.example.demo.bean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** * SpringBootDemo1 * Created by xian.juanjuan on 2017-6-13 13:31. */@Component@ConfigurationProperties(prefix = "book")public class BookInitBean {    private String name;    private String author;    public String getAuthor() {        return author;    }    public void setAuthor(String author) {        this.author = author;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

启动类

@RestController@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})public class SpringBootDemo1Application {   @Value("${book.author}")   private String bookAuthor;   @Autowired   private BookInitBean bookInitBean;   @RequestMapping("/")   String index(){      return "bookAuthor is " + bookAuthor+"; bookName is "+ bookInitBean.getName();   }   public static void main(String[] args) {      SpringApplication app = new SpringApplication(SpringBootDemo1Application.class);      app.run();   }}
访问


日志配置

logging:  file: D:/mylog/log.log  level: debug
Profile配置

Profile是用来针对不同环境的不同配置文件提供支持,如 application-dev.properties,通过在application.yml指定活动的Profile。

spring:  profiles:    active: dev



原创粉丝点击