Java 之 Spring Boot 配置

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

一、目录结构

Java 之 Spring Boot 配置_第1张图片

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

二、 安装依赖。

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


    org.projectlombok
    lombok
    1.18.12
    true

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

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


    org.springframework.boot
    spring-boot-configuration-processor
    true

三、使用

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

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

Java 之 Spring Boot 配置_第2张图片

创建一个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中的内容:

Java 之 Spring Boot 配置_第3张图片

同样创建一个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、结果

Java 之 Spring Boot 配置_第4张图片

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(java)