/WEB-INF フォルダーにある構成ファイルに依存する Spring Bean を定義するにはどうすればよいですか? 私の Bean の 1 つには、構成ファイルのファイル名を引数として取るコンストラクターがあります。
問題は、Spring IoC コンテナーをインスタンス化しようとしているときです - 失敗します。Spring IoC コンテナーが次の Bean を作成しようとすると、FileNotFound 例外が発生します。
<bean id="someBean" class="Bean">
<constructor-arg type="java.lang.String" value="WEB-INF/config/config.json"/>
</bean>
ContextLoaderListener を定義した web.xml ファイルの一部を次に示します。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
この場合の解決策はありますか?
// StackOverflow では質問に答えられないため、ここに解決策を投稿します。
解決策は、Bean クラスが次のインターフェースを実装する必要があることです - http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/ServletContextAware.html。Spring IoC コンテナーは、このインターフェースを実装するすべてのクラスに、ServletContext がインスタンス化されたことを通知します。次に、ServletContext.getRealPath メソッドを使用して、WEB-INF フォルダーのどこかにあるファイルへのパスを取得する必要があります。私の場合、Bean 構成ファイル beans.xml は同じままです。Bean クラスの最終バージョンを以下に示します。
public class Bean implements ServletContextAware {
private Map<String, String> config;
private ServletContext ctx;
private String filename;
public Bean(String filename) {
this.filename = filename;
}
public Map<String, String> getConfig() throws IOException {
if (config == null) {
String realFileName = ctx.getRealPath(filename);
try (Reader jsonReader = new BufferedReader(new FileReader(realFileName))) {
Type collectionType = new TypeToken<Map<String, String>>(){}.getType();
config = new Gson().fromJson(jsonReader, collectionType);
}
}
return config;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.ctx = servletContext;
}
}
これが誰かの助けになることを願っていますが、より良い解決策を知っている場合は共有してください。