Home > Software engineering >  How to set annotation values with properties
How to set annotation values with properties

Time:03-19

I want to set the value of an annotation depending on a "profile".

Let me explain with an example;

@Entity
//PROD
@Table(name="users", schema="JDEPRD")
//DEV
//@Table(name="users", schema="JDEDEV")

In the above example we can see that the active "profile" is PROD, but suppose that we want to use the DEV profile, we will have to comment the @Table annotation from PROD and uncomment the DEV @Table annotation.

If that was for only one entity that would be not a problem, but I have a lot of entities with this situation, so I do not believe that is the way to be working with this kind of improvised "profiles".

Do you know if there is any way to solve this situation?

CodePudding user response:

I would not include schema info with the table, I would control this with application.properties, having multiple profile-based properties.

spring.datasource.url=jdbc:postgresql://localhost:5432/schema-dev

Supplying your active profile runtime -Dspring.active.profile=dev

You could use https://www.baeldung.com/spring-profiles#3-multi-document-files or even multiple files.

my.prop=used-always-in-all-profiles
#---
spring.config.activate.on-profile=dev
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root
#---
spring.config.activate.on-profile=production
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

CodePudding user response:

Annotations are a compile-time concept and properties are a build-time or runtime concept. Since Annotations are, if configured that way, part of the class file it is not possible to change them during runtime.

But maybe you can change it with a library like cglib. BUT: as Raghu Dinka said it is much better to use two different databases or schemes. One for development and one for production. And this manipulation has to be done before the OR-Mapper analysis the classes.

Another way could be to implement a compiler plugin for the java compiler that changes the table definitions. But that's also not a good style.

  • Related