Spring-Boot:Profile简单示例

本文介绍如何在Spring Boot中使用不同的配置文件并实现属性注入。通过创建application.properties和application-prod.properties,设置激活的配置文件,并利用@ConfigurationProperties进行属性绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//Resources目录下创建 application.properties
spring.profiles.active=prod

 

//Resources目录下创建 application-prod.properties
book.name=spring boot prod

 

package com.example.entity;

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

/**
 * Created by liz19 on 2017/1/26.
 */
@Component
@ConfigurationProperties(prefix = "book")
public class Book {

    private String name;

    public String getName() {
        return name;
    }

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

 

package com.example;

import com.example.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableConfigurationProperties({Book.class})
public class DemoApplication {

    @Autowired
    private Book book;

    @RequestMapping("/")
    public Book index(){

        return book;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

1. spring.profiles.active 指定使用的profile

2. Book为配置类, profile中的配置对Book类进行注入

3. @ConfigurationProperties(prefix = "book") 开启配置文件管理并用前缀为book的值进行注入

 

转载于:https://www.cnblogs.com/MarchThree/p/6358594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值