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)