Spring boot使用自定义properties

spring boot使用application.properties默认了很多配置。但需要自己添加一些配置的时候,我们应该怎么做呢。
例如在application.properties配置文件中加入如下配置:
person.name=zhangsaninapplication
person.gender=maninapplication
那么如何在应用程序中进行读取呢?
首先定义配置读取实体类:
com.hpit.sb.properties.MyConfig

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

/**
 * TODO定义读取自定义配置类
 * 
 * @author郑江山
 *
 */

@ConfigurationProperties(prefix = "person") // 读取系统配置文件中的preson开头的所有配置,并自动封装到实体类中
public class MyConfig {

    private String name;
    private String gender;

    public MyConfig() {
    }

    public MyConfig(String name, String gender) {
        super();
        this.name = name;
        this.gender = gender;
    }

    public String getName() {
        returnname;
    }

    publicvoid setName(String name) {
        this.name = name;
    }

    public String getGender() {
        returngender;
    }

    publicvoid setGender(String gender) {
        this.gender = gender;
    }

}

添加@ConfigurationProperties注解用来读取application.properties配置文件中以person开头的所有配置。
2.在spring boot入口类加入:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
importorg.springframework.context.annotation.Bean;

import com.hpit.sb.properties.MyConfig;
importcom.hpit.sb.servlet.MyServlet1;

/**
 *
 *
 * 大家也许会看到有些demo使用了3个注解:@Configuration;
 *
 * @EnableAutoConfiguration
 * @ComponentScan其实:@SpringBootApplication申明让spring boot自动给程序进行必要的配置,
 *                等价于以默认属性使用@Configuration,
 * @EnableAutoConfiguration@ComponentScan 所以大家不要被一些文档误导了,让自己很迷茫了,希望本文章对您有所启发;
 *
 * @author郑江山
 */
@SpringBootApplication
@ServletComponentScan// 方式二:添加servlet注册扫描,将自动注册添加了@WebServlet的类为serlvet
@EnableConfigurationProperties(MyConfig.class) // 配置加载读取自定义配置类
public class App {

    /**
     * 方式一:注册Servlet.不需要添加注解:@ServletComponentScan 这种方式已经在springboot中废弃
     * 
     * @return
     */
    /*
     * @Bean public ServletRegistrationBean regMyServlet1() { return new
     * ServletRegistrationBean(new MyServlet1(), "/myServlet/*"); }
     */

    publicstaticvoid main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

}

如何是定义其他配置文件中,需要将实体类改写为:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值