Home > OS >  How do I make a String inside annotation depend on active profile?
How do I make a String inside annotation depend on active profile?

Time:02-12

I have an entity that needs to be mapped to a DynamoDBTable. We have two tables, one for dev environment and one for production. How can I change the string within an annotation depending on my current active profile?

In the dev enviroment I want the entity to start with this:

@DynamoDBTable(tableName = "my-dynamodbtable-dev")
public class MyEntity{

In the prod enviroment, I want it to start with this:

@DynamoDBTable(tableName = "my-dynamodbtable-prod")
public class MyEntity{

CodePudding user response:

Looks like you are creating separate table for DEV and PROD in same server. Ideally separate servers should be used for DEV and PROD.

Follow below steps to achieve your requirement in same server with different table for DEV and PROD:

Create an environment configuration as below:

(DEV)
    spring:
      profiles: DEV
    myEntity:
      tableName: my-dynamodbtable-dev
      
(PROD)
    spring:
      profiles: PROD
    myEntity:
      tableName: my-dynamodbtable-prod

Configure table as below to take table name at run time:

@DynamoDBTable(tableName = "${myEntity.tableName}")
public class MyEntity{
...
}

Provide default name as well like below to avoid statup issue in case config myEntity.table not available.

@DynamoDBTable(tableName = "${myEntity.tableName:my-dynamodbtable-dev}")
public class MyEntity{
...
}

CodePudding user response:

Can use below expression to arrive with values based on active profile:

@Value(#{'${spring.profiles.active}' eq 'PROD' ? 'my-dynamodbtable-prod' : 'my-dynamodbtable-dev'})
  • Related