質問

があるので、静的/世界的にリクエストフォームのApplicationContextの春。

仮にスクリプトの起動および初期化し、アプリケーションのコンテキストで合格する必要がありその呼び出しスタックに載の授業を必要とするので、このクラスをお願いすので構成された。(あるいはシングルトン?)

役に立ちましたか?

解決

場合、オブジェクトのニーズへのアクセスコンテナは、beanのコンテナで実施し BeanFactoryAware または ApplicationContextAware インタフェース

場合にはオブジェクト以外の容器のニーズへのアクセスコンテナを使い、 標準GoFシングルトンパターン springます。そしてワシングルトンのお申し込み探しも、予約も、支払も、全部エは全てシングルトン豆の容器です。

他のヒント

実践できる ApplicationContextAware ただ使用 @Autowired:

public class SpringBean {
  @Autowired
  private ApplicationContext appContext;
}

SpringBean してい ApplicationContext を注入し、このbeanがインスタンスを生成.例えば場合はウェブアプリケーションで写標準的階層:

main application context <- (child) MVC context

SpringBean が宣言された内本文脈でとらえるとして本文脈に注入;そうではない場合、この宣言された内MVC、いMVC文脈を噴射します。

このダイニングテーブル(ない鉱山、オリジナルの参照はこちら:http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html

に使用しましたが、この考え方です。基本的にこれは簡単な豆を実現したことにより(static)を参考にアプリケーションのコンテキスト.を参照この春configで初期化されます。

の原refでクリアになっています。

ダウンロードいただけまが利用可能 SingletonBeanFactoryLocator.のbeanRefFactory.xml ファイルが実際のapplicationContextうって思ったこと。

<bean id="mainContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
     <constructor-arg>
        <list>
            <value>../applicationContext.xml</value>
        </list>
     </constructor-arg>
 </bean>

このコードを取得し、beanから、applicationcontextからwhereeverのようなものになっていくかもこの:

BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bf = bfl.useBeanFactory("mainContext");
SomeService someService = (SomeService) bf.getFactory().getBean("someService");

春のチームのようにこのクラスを利用すとyadayada、その対応をしながらも、利用しています。

前を実装するその他の発案のもとに、自分自身に尋ねられ...

  • いたためることができるよう、ApplicationContext?
  • 私は、私の有効利用のApplicationContextサービスとしてロケータ?
  • できますか回避へのアクセスApplicationContextは全くないのでしょうか。

これらの問いへの答えは容易に特定の種類のアプリケーション(Webアプリなど)よりも他の人が分かります。

アクセスのApplicationContextな違反する全体依存性に注原則としてもいい手がけています。

ご利用の場合は、web-アプリもありますの別のアクセスのアプリケーションのコンテキストを使用せずにsingletons用servletfilter、ThreadLocal.フィルターにアクセスできるアプリケーションのコンテキストを使用WebApplicationContextUtils、店内のいずれかのアプリケーションのコンテキストまたは必要豆のTheadLocal.

注意:忘れてしまった場合は、設定を解除するThreadLocalを取得しま辺の問題にしようとした場合にアンデプロイします。このように設定すべきであるので、すぐに開始して試設定解除にThreadLocalの最後に-。

もちろん、これといってシングルトン:のThreadLocal.ですが、豆となります。においての要請-scoped、このソリューションも作品が複数ある場合には戦争を使用してアプリケーショるlibariesの終わりました。できます。性を高めることが考えられますがこの利用ThreadLocalどの平singletons.;-)

思春ている溶液とはなんですか?私を見つけられませんでしたがわからないですよね。

SpringApplicationContext.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Wrapper to always return a reference to the Spring Application 
Context from
 * within non-Spring enabled beans. Unlike Spring MVC's 
WebApplicationContextUtils
 * we do not need a reference to the Servlet context for this. All we need is
 * for this bean to be initialized during application startup.
 */
public class SpringApplicationContext implements 
ApplicationContextAware {

  private static ApplicationContext CONTEXT;

  /**
   * This method is called from within the ApplicationContext once it is 
   * done starting up, it will stick a reference to itself into this bean.
  * @param context a reference to the ApplicationContext.
  */
  public void setApplicationContext(ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  /**
   * This is about the same as context.getBean("beanName"), except it has its
   * own static handle to the Spring context, so calling this method statically
   * will give access to the beans by name in the Spring application context.
   * As in the context.getBean("beanName") call, the caller must cast to the
   * appropriate target class. If the bean does not exist, then a Runtime error
   * will be thrown.
   * @param beanName the name of the bean to get.
   * @return an Object reference to the named bean.
   */
  public static Object getBean(String beanName) {
    return CONTEXT.getBean(beanName);
  }
}

ソース: http://sujitpal.blogspot.de/2007/03/accessing-spring-beans-from-legacy-code.html

ContextSingletonBeanFactoryLocator.で静accessorsに対する支配を確立する春のコンテキストとして登録されている。

のではありませんで、より複雑でしょうか。

れることに注意してくださの保存状態から、現在の ApplicationContext, 又は ApplicationContext 体の静的変数の使用により、シングルトンパターンならば試験に不安定で不使用している場合は、泉コンテストを実施いたします。これは、Spring-試験キャッシュおよび再利用の申請コンテキストと同じJVM.例えば:

  1. 試験走行で含 @ContextConfiguration({"classpath:foo.xml"}).
  2. 試験Bでは含 @ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
  3. 試験Cでは含 @ContextConfiguration({"classpath:foo.xml"})

による試験で、 ApplicationContext を作成し、他の豆implemeting ApplicationContextAware やautowiring ApplicationContext もの静的変数となります。

による試験Bを同じようなことが起き、静的変数の現在ポイント試験B ApplicationContext

による試験C、 な豆を作成 としての TestContext (この ApplicationContext から試験はresused.または静的変数を指他 ApplicationContext では、現在開催のごテストです。

多くの取得アプリケーションのコンテキスト春ます。それ以下:

  1. 通ApplicationContextAware:

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class AppContextProvider implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    }
    

こちらの setApplicationContext(ApplicationContext applicationContext) 方法を取得しまapplicationContext

ApplicationContextAware:

インターフェースが実施するanyオブジェクトを希望する通知 のApplicationContextることです。このインタフェースの実施 というときの例外オブジェクトをアクセスする必要があるときのセット 研豆です。

  1. 通Autowired:

    @Autowired
    private ApplicationContext applicationContext;
    

こちらの @Autowired キーワードには、applicationContext.Autowiredつかの問題です。これらの成果を上問題になユニットテスト。

いはどのように役立つことができるものときに初期化します。この日は早く取得できコンテキストの前といえども @Autowire.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    private static ApplicationContext context;

    // I believe this only runs during an embedded Tomcat with `mvn spring-boot:run`. 
    // I don't believe it runs when deploying to Tomcat on AWS.
    public static void main(String[] args) {
        context = SpringApplication.run(Application.class, args);
        DataSource dataSource = context.getBean(javax.sql.DataSource.class);
        Logger.getLogger("Application").info("DATASOURCE = " + dataSource);

ご;以下のコードを新しいアプリケーションのコンテキストを利用する代わりに保存されています。

private static final ApplicationContext context = 
               new ClassPathXmlApplicationContext("beans.xml");

ることにも注意が beans.xml 含まれるべきである src/main/resources すること戦争の一部である、 WEB_INF/classes, ていたのに対して、実際のアプリケーショ読み込まれて applicationContext.xml お話ししたように、これまで Web.xml.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>META-INF/spring/applicationContext.xml</param-value>
</context-param>

であ 難しいapplicationContext.xmlClassPathXmlApplicationContext コンストラクタです。 ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml") ポ検出できるファイルです。

で用いる既存のapplicationContextを用いたアンソロジー。

@Component
public class OperatorRequestHandlerFactory {

    public static ApplicationContext context;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }
}

この問いに答えること間違いないでしょう株式のKotlinコードかを取得する春。

私は専門家ので、住所】高知県高知市大川筋における批評、レビューやアドバイス:

https://gist.github.com/edpichler/9e22309a86b97dbd4cb1ffe011aa69dd

package com.company.web.spring

import com.company.jpa.spring.MyBusinessAppConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.stereotype.Component
import org.springframework.web.context.ContextLoader
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.context.support.WebApplicationContextUtils
import javax.servlet.http.HttpServlet

@Configuration
@Import(value = [MyBusinessAppConfig::class])
@ComponentScan(basePackageClasses  = [SpringUtils::class])
open class WebAppConfig {
}

/**
 *
 * Singleton object to create (only if necessary), return and reuse a Spring Application Context.
 *
 * When you instantiates a class by yourself, spring context does not autowire its properties, but you can wire by yourself.
 * This class helps to find a context or create a new one, so you can wire properties inside objects that are not
 * created by Spring (e.g.: Servlets, usually created by the web server).
 *
 * Sometimes a SpringContext is created inside jUnit tests, or in the application server, or just manually. Independent
 * where it was created, I recommend you to configure your spring configuration to scan this SpringUtils package, so the 'springAppContext'
 * property will be used and autowired at the SpringUtils object the start of your spring context, and you will have just one instance of spring context public available.
 *
 *Ps: Even if your spring configuration doesn't include the SpringUtils @Component, it will works tto, but it will create a second Spring Context o your application.
 */
@Component
object SpringUtils {

        var springAppContext: ApplicationContext? = null
    @Autowired
    set(value) {
        field = value
    }



    /**
     * Tries to find and reuse the Application Spring Context. If none found, creates one and save for reuse.
     * @return returns a Spring Context.
     */
    fun ctx(): ApplicationContext {
        if (springAppContext!= null) {
            println("achou")
            return springAppContext as ApplicationContext;
        }

        //springcontext not autowired. Trying to find on the thread...
        val webContext = ContextLoader.getCurrentWebApplicationContext()
        if (webContext != null) {
            springAppContext = webContext;
            println("achou no servidor")
            return springAppContext as WebApplicationContext;
        }

        println("nao achou, vai criar")
        //None spring context found. Start creating a new one...
        val applicationContext = AnnotationConfigApplicationContext ( WebAppConfig::class.java )

        //saving the context for reusing next time
        springAppContext = applicationContext
        return applicationContext
    }

    /**
     * @return a Spring context of the WebApplication.
     * @param createNewWhenNotFound when true, creates a new Spring Context to return, when no one found in the ServletContext.
     * @param httpServlet the @WebServlet.
     */
    fun ctx(httpServlet: HttpServlet, createNewWhenNotFound: Boolean): ApplicationContext {
        try {
            val webContext = WebApplicationContextUtils.findWebApplicationContext(httpServlet.servletContext)
            if (webContext != null) {
                return webContext
            }
            if (createNewWhenNotFound) {
                //creates a new one
                return ctx()
            } else {
                throw NullPointerException("Cannot found a Spring Application Context.");
            }
        }catch (er: IllegalStateException){
            if (createNewWhenNotFound) {
                //creates a new one
                return ctx()
            }
            throw er;
        }
    }
}

現在、コンテキストが公開されている電話と同様の手法は独立したコンテキスト(junit試験、豆類、手動でインスタンスを生成クラス)のようにこのJava Servlet:

@WebServlet(name = "MyWebHook", value = "/WebHook")
public class MyWebServlet extends HttpServlet {


    private MyBean byBean
            = SpringUtils.INSTANCE.ctx(this, true).getBean(MyBean.class);


    public MyWebServlet() {

    }
}

いautowire春豆下記の通りとなります。@Autowired 民間のApplicationContext appContext;

ま、applicationcontextオブジェクトです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top