Spring 快速开始 Profile 和 Bean

时间:2023-03-08 18:42:28

和maven profile类似,Spring bean definition profile 有两个组件:声明和激活。

【栗子:开发测试环境使用HyperSQL 生产环境使用JNDI上下文根据配置查找数据库源】

<beans>

  <beans profile="development,qa">

    <jdbc:embedded-database id="dataSource" type="HSQL">

      <jdbc:script location="classpath:com/wrox/config/sql/schema.sql"/>

      <jdbc:script location="classpath:com/wrox/config/sql/test-data.sql"/>

    </jdbc:embedded-database>

  </beans>

  <beans profile="production">

    <context:property-placeholder location="file:/settings.properties" />

    <jee:jndi-lookup id="dataSource" jndi-name="java:/comp/env/${production.dsn}" />

  </beans>

</beans>

【栗子:@Configuration版本】

interface DataConfiguration{

  DataSource dataSource();

}

@Configuration

@Import({DevQaDataConfiguration.class,ProductionDataConfiguration.class})

@ComponentScan(basePackages = "com.wrox.site",excludeFilters = @ComponentScan.Filter(Controller.class))

public class RootContextConfiguration{}

@Configuration

@Profile({"development","qa"})

public class DevQaDataConfiguration implements DataConfiguration{

  @Override

  @Bean

  public DataSource dataSource(){

    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)

                      .addScript("classpath:com/wrox/config/sql/schema.sql")

                      .addScript("classpath:com/wrox/config/sql/test-data.sql")

                      .build();

  }

}

@Configuration

@Profile("production")

@PropertySource("file:settings.properties")

public class ProfuctionDataConfiguration implements DataConfiguration{

  @Value("production.dsr")

  String dataSourceName;

  @Override

  @Bean

  public DataSource dataSource(){

    return new JndiDataSourceLookup().getDataSource("java:/comp/env/"+this.dataSourceName);

  }

}

【激活profile】

1.应用程序级别激活

<context-param>

  <param-name>spring.profiles.active</param-name>

  <param-value>development</param-value>

</context-param>

2.Servlet级别激活

<servlet>

  <init-param>

    <param-name>spring.profiles.active</param-name>

    <param-value>development</param-value>

  </init-param>

3.运行时命令行参数激活  -Dspring.profiles.active=development

4.编程式激活 configurableEnvironment.setActiveProfiles("development");   将影响倒子应用上下文。

【profile细节】@Profile和@Component类似可以用作元数据注解,我们自己定义一个@Development注解。

@Documented

@Retention(value={ElementType.TYPE,ElementType.METHOD})

@Profile("development")

public @interface Development{}

【反模式和安全问题】当我们使用bean definition profile 解决问题要问自己。

1.有没有更简单的办法。如果多个profile创建的都是相同bean但使用的设置不同,这其实可以通过@PropertySource和properties文件完成。

2.profile中bean有哪些类型。大多数情况下,两个不同的profile具有的bean应该非常接近的,QA一搬和Prod一致,DEV和QA有一定区别。

3.安全意义?禁止去使用profile控制应用程序安全,因为终端用户可能会启用或禁用JVM命令行属性的方式   激活或冻结 profile,这样就绕过安全了。

一种比较傻叉的做法,dev禁用产品许可,qa和prod激活产品许可,聪明的用户只要将prod和qa切换回dev就能免费使用商业产品。