Java 之 Spring Boot 配置

写在前面:关于Spring Boot的hello word  网上一堆,所以这里并不是从hello world  起步,而是 从配置application.properties开始,毕竟一个项目开始,首先就要配置好数据库。

一、目录结构

可以看到,目前我配置了两个properties,这样也比较贴合实际需求,不可能把所有的配置全放application.properties中。

二、 安装依赖。

1、为了每个Bean不用写setter和getter,安装lombok

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <optional>true</optional>
</dependency>

安装后,在需要的Bean上面就可以使用@Data,然后就不用收些getter和setter了。

2、configuration-processor,这个是在使用出了application.properties时,指定文件路径的时候使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

三、使用

我想在TestController中使用application.properties 和 test.properties这两个配置文件。

1、先看看test.properties中的内容:

创建一个TestBean:

package com.dany.blog.bean;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component  -->跟Spring Boot说:我这里有个组件
@Configuration  -->是配置文件
@Data           -->不用自己写setter和getter了
@ConfigurationProperties(prefix = "test") -->刚才的那个test.properties中 内容中 前缀为test的。
@PropertySource("classpath:test.properties") -->指定这个配置在哪里
public class TestBean {
    private String level;
    private String name;
}

2、看看application.properties中的内容:

同样创建一个blogProperties的Bean,这个内容就比上面的那个少很多@了,因为SpringBoot默认就是找application.properties

 

package com.dany.blog.bean;

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


@Data
@Component
public class BlogProperties {

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


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

3、在TestControoler中使用

package com.dany.blog.controller;


import com.dany.blog.bean.BlogProperties;
import com.dany.blog.bean.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private TestBean testBean;

    @Autowired
    private BlogProperties blogProperties;

    @RequestMapping("/")
    public String index() {
        return "test name:"+testBean.getName()+"    blog的配置"+blogProperties.getName();
    }


}

4、结果

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值