springboot的两种配置文件 application.yml、application.properties、类型安全的配置

application.yml格式如下:

spring:
    mvc:
      view:
        suffix: .jsp
        prefix: /
    profiles:
      active: test
    datasource:
      type: com.alibaba.druid.pool.DruidDataSource
      url: jdbc:mysql://localhost:3306/test1
      driver-class-name: com.alibaba.druid.proxy.DruidDriver
      username: root
      password: root

mybatis:
  mapper-locations: com/lin/mapper/*.xml
  type-aliases-package: com.lin.entity

application.properties格式如下:

server.context-path=/test
server.port=8989

类型安全的配置:

1、在src/main/resources下创建book.properties

book.name=红楼梦
book.author=曹雪芹
book.price=28

2、创建Book Bean,并注入properties文件中的值(prefix是指前缀,location指定要注入文件的位置。)

@Component
@ConfigurationProperties(prefix = "book",locations = "classpath:book.properties")
public class BookBean {
    private String name;
    private String author;
    private String price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

3、在controller中注入bean

//一般从配置文件中获取值,没有值是为""
//@Value("${book.name:''}")
//private String bookName;


@Autowired
private BookBean bookBean;

@RequestMapping("/book")
	public String book() {
		return "Hello Spring Boot! The BookName is "+bookBean.getName()+";and Book Author is "+bookBean.getAuthor()+";and Book price is "+bookBean.getPrice();
	}

 


版权声明:本文为weixin_43240792原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。