Deltaspike + Quartz + CronExpressions from custom

2019-09-13 10:59发布

问题:

I've achieved configuring CronExpression from a propery file, but this property file is apache-deltaspike.properties, which is inside the .jar file. I need to take the cron expression from my custom config file:

import org.apache.deltaspike.core.api.config.PropertyFileConfig;

public class myOwnPropertyFileConfig  implements PropertyFileConfig  {
  private static final long serialVersionUID = 1L;

  @Override
  public String getPropertyFileName() {
    return "cfg/myOwnPropFile.properties";
  }

  @Override
  public boolean isOptional() {
    return false;
  }

}

myOwnPropFile.properties

deltaspike_ordinal=500
property1=value1
property2=value2
QuartzJob=0 25 17 * * ?

the job:

@Scheduled(cronExpression = "{QuartzJob}")
public class MyQuartzJob implements Job {
  //job code
}

Everything goes good when I set this property: QuartzJob=0 25 17 * * ? inside apache-deltaspike.properties, but when I set it in my own property file, I get:

java.lang.IllegalStateException: No config-value found for config-key: QuartzJob 

Researching, I found that my property file is loaded right after Quartz initialization, and that explains the why. Now, I read in Deltaspike doc that it's possible to get my property file loaded whenever I want, using deltaspike_ordinal inside my property file. So I tried, but it seems to ignore the deltaspike_ordinal=500, and error keeps arising.

So, does someone know how to sort this out? Deltaspike doc also talks about a ConfigSource and so, but it's not so clear and there are no examples.

Thanks in advance!

回答1:

Got it. The key was to look into the javadoc of PropertyFileConfig:

  1. Automatic pickup via java.util.ServiceLoader mechanism In case you have an EAR or you need the configured values already during the CDI container start then you can also register the PropertyFileConfig via the java.util.ServiceLoader mechanism. To not have this configuration picked up twice it is required to annotate your own PropertyFileConfig implementation with org.apache.deltaspike.core.api.exclude.Exclude.

The ServiceLoader mechanism requires to have a file META-INF/services/org.apache.deltaspike.core.api.config.PropertyFileConfig containing the fully qualified Class name of your own PropertyFileConfig implementation class.
com.acme.my.own.SomeSpecialPropertyFileConfig The implementation will look like the following:

@Exclude
  public class SomeSpecialPropertyFileConfig implements PropertyFileConfig      {
      public String getPropertyFileName() {
          return "myconfig/specialconfig.properties"
      }
      public boolean isOptional() {
          return false;
      }
  }

Worked like a charm