Springboot学习笔记(九)——Profiles
1.为什么要使用Profiles
在开发中,一般有两种环境
1,生产环境 [项目上线,客户在使用中,就是生产环境]
2,开发环境[就是开发环境,不解释]
有时候开发环境和生产环境的配置方法是不一样的,那么如何快速的切换呢,这里就要使用profiles文件。
2.使用@Profile注解来实现
在service包下创建一个TestService类来测试Profile;
代码如下:
public class TestService { private String password; TestService(String password) { this.password = password; } public String testProfiles() { return password; } }
在AppConfig类中添加如下代码:
@Configuration public class AppConfig { @Bean @Profile("dev") public TestService testServiceDev() { return new TestService("devpassword"); } @Bean @Profile("prob") public TestService testServiceProb() { return new TestService("probpassword"); } }
在controller类中添加一个映射方法。代码如下:
@RestController public class UserController { @Autowired private UserService userService; @Autowired private TestService testService; @RequestMapping("/") String home() { return userService.test(); } @RequestMapping("/profiles") String testProfiles() { return testService.testProfiles(); } }
在application.properties文件中添加下列属性
spring.profiles.active=prob
在浏览器中访问就会发现用的是@Profile("prob")这个bean
3.使用不同的xml方式来实现