springboot profile 使用


springboot profile 使用

 

作用:在不同的profile(如开发、测试)中使用不同的bean、属性文件

 

 

************************

bean profile

 

***************

pojo 层

 

Person

@Data
public class Person {

    private Integer id;
    private String name;
    private Integer age;
}

 

***************

config 层

 

DataConfig

@Configuration
public class DataConfig {

    @Bean
    @Profile("prod")
    public Person initPerson(){
        Person person=new Person();
        person.setId(1);
        person.setName("瓜田李下");
        person.setAge(24);

        return person;
    }

    @Bean
    @Profile("test")
    public Person initPerson2(){
        Person person=new Person();
        person.setId(1);
        person.setName("海贼王");
        person.setAge(20);

        return person;
    }
}

 

***************

controller 层

 

HelloController

@RestController
public class HelloController {

    @Resource
    private Person person;

    @RequestMapping("/hello")
    public Person hello(){
        System.out.println(person);

        return person;
    }
}

 

*************************

控制台输出

 

application.yml中设置:

spring:
  profiles:
    active: prod

**********************
控制台输出:

Person(id=1, name=瓜田李下, age=24)

 

application.yml中设置:

spring:
  profiles:
    active: test

******************
控制台输出:

Person(id=1, name=海贼王, age=20)

 

 

************************

属性文件 profile

 

属性文件:application-prod.yml

server:
  port: 8081

 

属性文件:application-test.yml

server:
  port: 8082

 

application.yml中设置profiles为prod:

spring:
  profiles:
    active: prod

********************
控制台启动输出:

2019-12-15 16:58:07.792  INFO 520 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-15 16:58:07.912  INFO 520 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2019-12-15 16:58:07.915  INFO 520 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 1.669 seconds (JVM running for 3.192)

 

application.yml中设置profiles为test:

spring:
  profiles:
    active: test

*********************
控制台启动输出:

2019-12-15 17:03:22.315  INFO 23660 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-15 17:03:22.449  INFO 23660 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8082 (http) with context path ''
2019-12-15 17:03:22.453  INFO 23660 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 1.978 seconds (JVM running for 3.597)

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值