spring boot 在框架中注入properties文件里的值

前一篇博客实现了打开第一个页面

链接:https://blog.csdn.net/qq_38175040/article/details/105709758

本篇博客实现在框架中注入properties文件中的值

首先在resource下创建一个book.properties文件,如下:
在这里插入图片描述

然后创建一个bookbean.java文件,如下,我把代码贴一下:
在这里插入图片描述

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "book")
@PropertySource("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;
    }
}

这里要注意 @ConfigurationProperties的写法
旧版本的写法是:@ConfigurationProperties(prefix = “book”,locations = “classpath:book.properties”)
现在我们这样写:
@ConfigurationProperties(prefix = “book”)
@PropertySource(“classpath:book.properties”)

最后一步

DemoApplication.java(每个人命名的可能不一样) 中添加如下内容:
在这里插入图片描述

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

好了,现在打开页面看看效果:
在这里插入图片描述
更多细节可以参考:https://blog.csdn.net/u012702547/article/details/53740047

ok,这不就行了吗,要的就是这个效果

发布了20 篇原创文章 · 获赞 3 · 访问量 1130

猜你喜欢

转载自blog.csdn.net/qq_38175040/article/details/105723124
今日推荐