SpringBoot开发过程之一

本文详细介绍如何在Spring Boot项目中创建实体类并使用@ConfigurationProperties进行属性配置,通过@Controller注解实现属性值的获取与展示。

项目搭建

创建完成

编写一个简单的类然后在配置文件设置属性,在controller中获取该属性值

写一个studnet实体类

package com.bdqn.spring_boot_10_31_5.entity;

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

//实体类注入容器
@Component
//将该对象实例一个对象给容器,可以在配置文件中进行配置,student是统一的
@ConfigurationProperties(prefix="student")
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {

    }

    public String getName() {

        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

在实体类上交以后然后在配置文件中可以进行属性配置

student.name=jin
student.age=19

最后写controller

package com.bdqn.spring_boot_10_31_5.controller;

import com.bdqn.spring_boot_10_31_5.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class getStudent {
    //自动注入
    @Autowired
    private Student student;
    
    //外部访问路径
    @RequestMapping("/sayHello")
    //设置返回的方式,该注解是返回给访问对象string字符串
    @ResponseBody
    public String show(){
        return "获取到"+student.getName()+student.getAge();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值