2017-11-13 6 views
0

Java Spring WebプロジェクトでServletContextを取得し、 を使用してWebアプリケーションプロジェクトの絶対パスを取得します。私はまだJavaEEとSpringで 初心者ですので、多分いくつかの概念が間違っています。 ServletContextを使用したいJavaクラスでは、@Autowired ServletContextコンテキストを使用するときに が空のオブジェクトだけを取得します。 WebMvcConfigurerAdapterクラスを継承するRestConfiguartionクラスでServletContextを取得しましたが、 はServletContextの戻り値の型でJava Beanで使用することができます。しかし、私は は考えていない、どのように私は ServletContextを得るために別のクラスでBeanを使用することができます、これは可能ですか?SpringはServletContextを取得してBeanとして提供します

@Configuration 
@EnableWebMvc 
@Import({ ServiceConfiguration.class, SecurityConfiguration.class }) 
@ComponentScan(basePackages = { "de.rest", "de.security" }) 
public class RestConfiguration extends WebMvcConfigurerAdapter { 

    @Autowired 
    ServletContext context;  

    @Bean 
    public ServletContext getServletContext() { 
    System.out.println("*** Context path: *** " + context.getRealPath("/")); 
    return context; 
    }} 

答えて

0

あなたも他のBeanの注釈付きのクラスでは

@Autowired 
ServletContext context; 

を書くことができます。あなたは同じ文脈を得るでしょう。 そのので、あなたは指定する必要はありません:たとえば

@Bean 
    public ServletContext getServletContext() { 
    System.out.println("*** Context path: *** " + context.getRealPath("/")); 
    return context; 
    }} 

(あなたの注釈@ComponentScanに指定されたディレクトリ内の任意のクラス、):私は解決してきたあなたの助けに

@Bean 
class X { 
    @Autowired 
    ServletContext context; 

    ... 
} 
0

感謝を@ComponentScanにターゲットクラスのパッケージを追加し、ターゲットクラス@Componentを宣言し、前に使用したBeanを挿入しました。結果は次のコードスニペットです。

... 
@ComponentScan(basePackages = { "de.rest", "de.security", "de.targetPackage" }) 
public class RestConfiguration extends WebMvcConfigurerAdapter { 
... 



@Component 
public class targetClass { 

    private static String absoluteServletContextPath; 

    @Autowired 
    ServletContext context; 

    @Bean 
    public ServletContext getServletContext() { 
    absoluteServletContextPath = context.getRealPath("/"); 
    System.out.println(absoluteServletContextPath); 
    return context; 
    } 

    @Override 
    public void myMethod { 

     absoluteServletContextPath = absoluteServletContextPath.replaceAll("webapp\\\\", "") 
      .replaceAll("\\\\", "/");}}