简体   繁体   English

如何使用属性设置注释值

[英]How to set annotation values with properties

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.在上面的示例中,我们可以看到活动的“配置文件”是 PROD,但是假设我们要使用 DEV 配置文件,我们将不得不从 PROD 注释 @Table 注释并取消注释 DEV @Table 注释。

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?你知道有什么办法可以解决这种情况吗?

I would not include schema info with the table, I would control this with application.properties, having multiple profile-based properties.我不会在表中包含架构信息,我会使用 application.properties 来控制它,它具有多个基于配置文件的属性。

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

Supplying your active profile runtime -Dspring.active.profile=dev提供您的活动配置文件运行时-Dspring.active.profile=dev

You could usehttps://www.baeldung.com/spring-profiles#3-multi-document-files or even multiple files.您可以使用https://www.baeldung.com/spring-profiles#3-multi-document-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

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.如果以这种方式配置注释,则注释是 class 文件的一部分,因此无法在运行时更改它们。

But maybe you can change it with a library like cglib.但也许你可以用像 cglib 这样的库来改变它。 BUT: as Raghu Dinka said it is much better to use two different databases or schemes.但是:正如 Raghu Dinka 所说,使用两个不同的数据库或方案要好得多。 One for development and one for production.一个用于开发,一个用于生产。 And this manipulation has to be done before the OR-Mapper analysis the classes.这种操作必须在 OR-Mapper 分析类之前完成。

Another way could be to implement a compiler plugin for the java compiler that changes the table definitions.另一种方法是为 java 编译器实现一个编译器插件来更改表定义。 But that's also not a good style.但这也不是一个好的风格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM