当我尝试运行spring boot应用程序时。
在具有属性spring.profiles.active=production的application.properties文件中有一个属性可用。
当我在网上搜索关于这个属性的详细信息时,我知道了spring.profiles.active=local。
有人能解释一下这些细节吗?
发布于 2017-06-25 06:58:04
当应用程序从开发过渡到生产时,为开发所做的某些特定于环境的选择是不合适的,或者是不起作用的。
例如,考虑数据库配置。在开发环境中,您可能会使用预先加载了测试数据的嵌入式数据库,如下所示:
@Bean(destroyMethod="shutdown")
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.addScript("classpath:schema.sql")
.addScript("classpath:test-data.sql")
.build();
}在生产环境中,您可能希望使用JNDI从容器中检索DataSource:
@Bean
public DataSource dataSource() {
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/myDS");
jndiObjectFactoryBean.setResourceRef(true);
jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
return (DataSource) jndiObjectFactoryBean.getObject();
}从Spring3.1开始,您可以使用配置文件。Method-leve @Profile注解从Spring3.2开始工作。在Spring3.1中,它只是类级别的。
@Configuration
public class DataSourceConfig {
@Bean(destroyMethod="shutdown")
@Profile("development")
public DataSource embeddedDataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql")
.addScript("classpath:test-data.sql")
.build();
}
@Bean
@Profile("production")
public DataSource jndiDataSource() {
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/myDS");
jndiObjectFactoryBean.setResourceRef(true);
jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
return (DataSource) jndiObjectFactoryBean.getObject();
}
}每个DataSource bean都在一个配置文件中,只有在规定的配置文件处于活动状态时才会创建它们。任何未指定配置文件的bean都将被创建,而不管哪个配置文件是活动的。
您可以为您的配置文件指定任何逻辑名称。
发布于 2017-06-25 09:28:41
您可以使用此属性让Spring知道哪些配置文件应该是活动的(在启动应用程序时使用)。例如,如果您在application.properties中或通过参数-Dspring.profiles.active=prod给出它;您告诉Spring在prod配置文件下运行。这意味着- Spring将查找"application-prod.yml“或”application-prod.properties“文件,并加载该文件下的所有属性。
您还可以通过@ profile ("PROFILE_NAME")注释bean (方法或类)-这确保了bean被映射到特定的profile。
您可以将多个配置文件传递给spring.profiles.active。
有关更多信息,请参阅文档- https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html
https://stackoverflow.com/questions/44741577
复制相似问题