定数を使用してプロパティを定義し、@Value アノテーションで解決しようとしています。
インターフェイスで定数を定義しました:
public interface InternalConstant{
public static final String JOB_NAME_PROPERTY = "javabatch.jobName";
}
私はspringbootを使用しており、プロパティをデフォルトのプロパティとしてコンテキストに追加しています:
SpringApplication springApp = new SpringApplication(configs.toArray());
Properties props = new Properties();
props.setProperty(InternalConstants.JOB_NAME_PROPERTY, "MyStartableJob");
springApp.setDefaultProperties(props);
ここで、@Value を使用して、文字列「MyStartableJob」を文字列に挿入したいと思います。しかし、直接使用する代わりに@Value(value="${javabatch.jobName})
、定義済みの定数を使用したいと思います。
私は試した
@Value(value="#{T(ch.mobi.javabatch.core.internal.InternalConstants).JOB_NAME_PROPERTY}")
もちろん、これは「javabatch.jobName」にのみ解決され、「javabatch.jobName」という名前のプロパティの値には解決されません。
だから私はそれをラップしようとしました@Value(value="${#{T(ch.mobi.javabatch.core.internal.InternalConstants).JOB_NAME_PROPERTY}}")
が、これは例外を引き起こします。
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder '#{T(ch.mobi.javabatch.core.internal.InternalConstants).JOB_NAME_PROPERTY}' in string value "${#{T(ch.mobi.javabatch.core.internal.InternalConstants).JOB_NAME_PROPERTY}}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:801)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:955)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 16 more
環境を単純に注入し、その getProperty メソッドを使用できることはわかっています。
@Autowired
private Environment env;
public void m1() {
env.getProperty(InternalConstants.JOB_NAME_PROPERTY);
}
これは機能し、私の目的を果たします。しかし、@Value で SPEL を使用してこれを行うこともできるのではないかと思います。
ありがとう。