Spring Boot - How to read application.properties in custom sequence generator which used in @GenericGenerator

575 Views Asked by At

I created a CustomSequenceGenerator for my model, everything is working fine.

Now i'm trying to read value from application.properties inside the CustomSequenceGenerator but failed.

I have tried many ways suggested by stackoverflow but still no luck on this.

1. Using @Value
2. Using Spring Environment env > env.getProperty()
3. Using @ConfigurationProperties
4. Using @PropertySource

Here is my codes:

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;

CustomSequenceGenerator

public class CustomSequenceGenerator implements IdentifierGenerator, Configurable {

    @Value("${seq.prefix}")
    private String sequencePrefix;

    .......
}

I put a break point on my CustomSequenceGenerator and i noticed that it jumps into the break point during server startup, so i guess that spring is not able to read the application.properties during startup/initialization.

application.properties

located in Resources/conf/application.properties, I have specify the location using -Dspring.config.location and other controllers have no problem in accessing the properties file, just CustomSequenceGenerator is having issue.

....
spring.jpa.show-sql=true
seq.prefix = MOCKDB.MOCK_SCHEMA.
....

So how can i read the properties value in this case ?

Thank you.

1

There are 1 best solutions below

0
mo1ot On

You can use System Properties to pass your value from application.properties

   @Component
    public class PropertiesConfig {
    
        @Value("${z.prefix}")
        private String zPrefix;
    
        @PostConstruct
        public void setProperty() {
            System.setProperty("z.prefix", zPrefix);
        }
    }

And then read it in your custom generator

var zPrefix = System.getProperty("z.prefix");