Spring boot自定义 文件.properties 查询

***Spring boot 使用Idea编辑器 自定义配置xxx.properties***并且从网页查出
首先在pom.xml中添加依赖

在这里插入代码片
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

第一步加入依赖已完成,下一步自定义xxx.properties
d点击ianji这里插入图片描述
点击resources 上方红色箭头,鼠标右击 下方图片
在这里插入图片描述
创建好之后 在里写上简单入门的小方法
在这里插入图片描述

最后写代码`


package com.demo12.demo.Bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:daren.properties")
@ConfigurationProperties(prefix = "demo")
public class darenBean {
    private String name;
    private String age;
    private String sex;

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}







```html
在这里插入代码片

自定义配置的属性绑定JavaBean
   这种情况与之前的基本相同,只是不能自动加载,需要手动加载,在JavaBean之上加上之前介绍的@PropertySource注解进行配置文件加载。还有一点就是将@Component改为@Configuration,为什么这么做呢?
  
   @Configuration注解的底层就是@Component,但是二者意义不同,@Configuration注解侧重配置之意,@Component侧重组件之意,当然配置也是项目组件之一,在这里我们要将配置文件属性与JavaBean绑定,当然更侧重配置之意。
  
  将配置与JavaBean绑定之后,我们就可以通过JavaBean来获取配置的内容,而且JavaBean已经被@Component注解或者@Configuration注解加载到Spring容器,我们可以使用自动注入的方式在其他类中随便使用。
   这里要注意一点:当我们在某个类中要使用这个JavaBean时,需要在这个类中指定这个JavaBean的类型,这个指定也要使用注解来指定,正是之前介绍的@EnableConfigurationProperties注解,这个注解与@ConfigurationProperties注解配套使用。

在这里插入代码片

package com.demo12.demo.Controller;

import com.demo12.demo.Bean.darenBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hao")
@EnableConfigurationProperties(darenBean.class)
public class darenController {
    @Autowired
    darenBean darenBean;
    @RequestMapping("/ni")
    public String ni(){
        return "姓名"+darenBean.getName()+"年龄"+darenBean.getAge()+"性别"+darenBean.getSex();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值