day4--springboot学习--第二章springboot入门--动力节点

从配置文件中取数据

设置数据:

#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot

#自定义key=value
school.name=动力节点
school.website=www.bjpowernode.com
school.address=北京大兴区

site=www.baidu.com

在Controller中获取值:

package com.example.Controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    //获取值
    @Value("${server.port}")
    private Integer port;
    //这个时候application.properties里定义的server.port的值就赋值给了port

    @Value("${server.servlet.context-path}")
    private String contextPath;

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

    @Value("${school.website}")
    private String website;

    @Value("${site}")
    private String site;

    @RequestMapping("/data")
    @ResponseBody
    public String queryData(){
        return name+",site"+site+",项目的访问地址:"+contextPath+",我们使用的端口:"+port;
    }
}

结果

 二、把配置文件的数据映射为java对象

package com.example.vo;

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

@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
    private String name;
    private String website;
    private String address;

    public String getName() {
        return name;
    }

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

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "SchoolInfo{" +
                "name='" + name + '\'' +
                ", website='" + website + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

 其中@Component是创建子类对象

@ConfigurationProperties(prefix = "school")是从配置文件中找到school开头的值

 在Controller中调用(其中@Resource表示自动注入,先byname,再bytype)

 

 

 

 27 手工获取容器中对象,早springboot中使用ApplicationContext

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值