2

私のコントローラーは

@Value("${myProp}")
private String myProp;

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
}

@RequestMapping(value = "myProp", method = RequestMethod.GET)
public @ResponseBody String getMyProp(){
    return "The prop is:" + myProp;
}

私のapplicationcontext.xml持っている

<bean id="appConfigProperties" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value="classpath:MyApps-local.properties" />
</bean>

次の例外が発生します。

原因: java.lang.IllegalArgumentException: 文字列値 "${myProp}" のプレースホルダー 'myProp' を解決できませんでした

注:私のプロパティファイルMyApps-local.propertiesはにありclasspath、含まれています myProp=delightful

どんな助けでも素晴らしいでしょう....

4

4 に答える 4

1

構成には、2 つの PropertySourcesPlaceholderConfigurer があります。Java @Configuration を使用して DispatcherServlet で定義された最初のものは、標準環境を使用してプロパティを検索します。これは、システム環境と環境変数、および定義された @PropertySource からのプロパティを意味します。

これは、applicationContext.xml で指定された MyApps-local.properties ファイルを認識しません。xml ファイルの 2 番目の PropertySourcesPlaceholderConfigurer は MyApps-local.properties ファイルを認識していますが、ルート アプリケーション コンテキストのポスト プロセス プレースホルダーのみです。

Bean ファクトリ ポスト プロセッサは、アプリケーション コンテキストごとにスコープが設定されます。

Web アプリケーション コンテキストを変更して、プロパティ ソースを指定します。これにより、ファイル内のプロパティが環境に追加されます。

@Configuration
@PropertySource("classpath:MyApps-local.properties")
public class WebConfig{
   @Autowired
   private Environment env;

   @RequestMapping(value = "myProp", method = RequestMethod.GET)
   public @ResponseBody String getMyProp(){
       return "The prop is:" + env.getProperty("myProp");
   }
 }

この場合、環境からプロパティを照会できるため、PropertySourcesPlacheholder は必要ありません。次に、applicationContext.xmlをそのままにしておきます

また、環境からプロパティを選択するため、PropertySourcesPlaceholder @Bean でも機能します。ただし、上は下よりきれいです

@Configuration
@PropertySource("classpath:MyApps-local.properties")
public class WebConfig{

   @Value("${myProp}")
   private String myProp;

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
     return new PropertySourcesPlaceholderConfigurer();
   }

   @RequestMapping(value = "myProp", method = RequestMethod.GET)
   public @ResponseBody String getMyProp(){
     return "The prop is:" + myProp;
   }
}
于 2016-06-02T16:56:15.770 に答える
0

See if this helps

  1. You could go on and use this util tag in your xml configuration

<util:properties id="appConfigProperties" location="location to your properties file" /> <context:property-placeholder properties-ref="appConfigProperties" />

  1. Comes from schema http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd

  2. Then in you code where you want your value from property file use it as

@Value("${myPropl}")
private String str;

works for me, let me know if stuck any where :)

于 2016-06-02T18:38:31.967 に答える