36

コンストラクターを呼び出すことによってインスタンス化されるクラス (クラス ABC) があります。クラス ABC には、自動配線を使用して挿入されたヘルパー クラス (クラス XYZ) があります。

私たちのものはSpring MVCベースのアプリケーションで、サーバーの起動中に例外は見られません.

しかし、クラス XYZ が null として表示されます。クラス ABC が Spring Container によってインスタンス化されていないためでしょうか?

このようなシナリオでは、自動配線をどのように利用すればよいですか?

ありがとう。

4

10 に答える 10

47

この方法を使用して、非Spring BeanクラスでSpring Beanを使用できます

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtils implements ApplicationContextAware {
     
      private static ApplicationContext ctx;
     
      @Override
      public void setApplicationContext(ApplicationContext appContext) {
        ctx = appContext;
      }
     
      public static ApplicationContext getApplicationContext() {
        return ctx;
      }
}

これで、このメソッド getApplicationContext() によって applicationcontext オブジェクトを取得できます。

applicationcontext から、次のような Spring Bean オブジェクトを取得できます。

ApplicationContext appCtx = ApplicationContextUtils.getApplicationContext();
String strFromContext = appCtx.getBean(beanName, String.class);
于 2013-08-28T11:06:46.157 に答える
4

他の Bean を自動配線するクラスで、Spring の @Configurable アノテーションを使用できます。さらに、Spring が構成可能な Bean を認識できるように、構成 Bean に @EnableSpringConfigured でアノテーションを付ける必要があります。

@EnableSpringConfigured ドキュメント

public @interface EnableSpringConfigured Spring Bean ファクトリの外部でインスタンス化された管理されていないクラス (通常は @Configurable アノテーションが付けられたクラス) に依存性注入を適用するために、現在のアプリケーション コンテキストにシグナルを送信します。Spring の XML 要素に見られる機能に似ています。@EnableLoadTimeWeaving と組み合わせて使用​​されることがよくあります。

@Configurable(autowire = Autowire.BY_TYPE)
public class ABC {
    @Autowire private XYZ xyz;
    ...
}

@Configuration
@EnableSpringConfigured
public class Application {
    ...
}

public class MyClass {
    public void doSomething() {
        ABC abc = new ABC(); // XYZ is successfully autowired
        ...
    }
}
于 2016-09-13T18:31:58.710 に答える
4

正解: クラスを呼び出しnewてすべてを接続することはできません。Bean がすべての魔法を実行するには、Spring が Bean を管理する必要があります。

ユースケースの詳細を投稿していただければ、有用なオプションを提案できる場合があります。

于 2013-08-21T01:45:12.930 に答える
2

要するに、はい、Spring が ABC を管理していないため、ABC に XYZ が注入されていません。Spring は、知らないオブジェクトを構成することはできません。

@Serviceまたはで注釈を付けることで、ABC を管理でき@Componentます。Spring がこれらのアノテーションを取得するには、Spring で自動スキャンがオンになっている必要があることに注意してください。

<context:component-scan base-package="com.mypackage.awesomeproject" />
于 2013-08-21T01:45:27.597 に答える
1

最初の質問 - はい、クラスは春で開始されていないため、null があります 2 番目の質問 -アスペクトj サポートを使用できると思います.html#aop-using-aspectj

于 2013-08-21T07:52:50.380 に答える
0

ABCクラスに注釈を付けることができます@Configurable。次に、Spring IOC はXYZインスタンスをABCクラスに注入します。通常、 AspectJ で使用されAnnotationBeanConfigurerAspectます。

于 2013-08-21T08:56:58.853 に答える