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();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值