SpringBoot讀取properties中的屬性值

1.在application.properties中添加如下內容:web

learn.blog.name=hello
learn.blog.title=千回教育系統

2.新增屬性關聯的類:spring

package com.czhappy.learn.BootLearn.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class BlogProperties {

    @Value("${learn.blog.name}")
    private String name;

    @Value("${learn.blog.title}")
    private String title;

    public String getName() {
        return name;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

3.編寫controller:瀏覽器

package com.czhappy.learn.BootLearn.controller;

import com.czhappy.learn.BootLearn.config.BlogProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {
    @Autowired
    private BlogProperties blogProperties;

    @RequestMapping("/")
    String index() {
        System.out.println(blogProperties.getTitle());
        return blogProperties.getName()+"——"+blogProperties.getTitle();
    }
}

4.啓動應用,在瀏覽器中調用:app

 

注意事項:ide

若是瀏覽器中顯示中文亂碼,須要修改idea的配置:this

而後複製application.properties文件中的內容並保存到一個臨時文本中,把application.properties文件刪除,在原目錄從新新建一個application.properties,把臨時文本中的內容copy到新建的application.properties文件中,啓動項目,便可正確獲取中文內容。idea

相關文章
相關標籤/搜索