[英]Spring Boot - How to read application.properties in custom sequence generator which used in @GenericGenerator
我为我的 model 创建了一个 CustomSequenceGenerator,一切正常。
现在我正在尝试从 CustomSequenceGenerator 中的 application.properties 中读取值,但失败了。
我尝试了stackoverflow建议的许多方法,但仍然没有运气。
1. Using @Value
2. Using Spring Environment env > env.getProperty()
3. Using @ConfigurationProperties
4. Using @PropertySource
这是我的代码:
Model
@Id
@GenericGenerator(name = "user_id_gen", strategy="com.my.model.common.CustomSequenceGenerator ",
parameters = {
@org.hibernate.annotations.Parameter(name = "sequence_name", value = "USER_SEQ")}
)
@GeneratedValue(generator = "user_id_gen")
@Column(name = "UserId", unique = true, nullable = false, length = 6)
private String userId;
自定义序列生成器
public class CustomSequenceGenerator implements IdentifierGenerator, Configurable {
@Value("${seq.prefix}")
private String sequencePrefix;
.......
}
我在我的 CustomSequenceGenerator 上放了一个断点,我注意到它在服务器启动期间跳入断点,所以我猜 spring 在启动/初始化期间无法读取 application.properties。
应用程序属性
位于Resources/conf/application.properties
,我已经使用-Dspring.config.location
指定了位置,其他控制器在访问属性文件时没有问题,只是 CustomSequenceGenerator 有问题。
....
spring.jpa.show-sql=true
seq.prefix = MOCKDB.MOCK_SCHEMA.
....
那么在这种情况下我如何读取属性值呢?
谢谢你。
您可以使用系统属性从 application.properties 传递您的值
@Component
public class PropertiesConfig {
@Value("${z.prefix}")
private String zPrefix;
@PostConstruct
public void setProperty() {
System.setProperty("z.prefix", zPrefix);
}
}
然后在您的自定义生成器中阅读它
var zPrefix = System.getProperty("z.prefix");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.