当我尝试运行Spring Boot应用程序时。
application.properties
文件中有一个属性,其中它具有属性spring.profiles.active=production
。
在网络中搜索有关此属性的详细信息时,我知道spring.profiles.active=local
。
任何人都可以解释这些细节吗?
为开发做出的某些特定环境特定选择是不合适的,或者在从开发到生产的申请过渡时无法正常工作。
例如,考虑数据库配置。在开发环境中,您可能会使用预装的嵌入式数据库,并使用类似的测试数据:
@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();
}
从弹簧3.1开始,您可以使用配置文件。方法 - leve @Profile
从春季3.2开始。在春季3.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都将始终创建,而不管哪个配置文件有效。
您可以为您的配置文件提供任何逻辑名称。
您可以使用此属性让Spring知道哪些配置文件应处于活动状态(在启动应用程序时要使用(。例如,如果您在application.properties或通过参数-dspring.profiles.active.active = prod中给予它。您告诉Spring,在Prod Profile下运行。这意味着 - Spring将寻找" application-prod.yml"或" application-prod.properties"文件,并将加载下面的所有属性。
您还可以通过@profile(" profile_name"(注释bean(方法或类( - 这确保了bean映射到某些profile。
您可以将多个配置文件传递到spring.profiles.active。
文档中的更多信息-https://docs.spring.io/spring-boot/docs/current/referent/reference/html/boot-features-profiles.html