2

私はSpring 3の注釈駆動型コントローラーとサービスのいくつかを扱っていますが、これがどのように可能になるかについて質問がありましたか?

  1. 私のservlet-context.xmlファイルには、次のアイテムをロードするためのパスがあります。

    <context:component-scan base-package="com.project.controller, com.project.service"/>

コントローラーの下では、init クラスにこれがあり、init は次のようにタグ付けされています。

@PostConstruct
public void init() {
    ApplicationContext context = new GenericApplicationContext();
    bizServices = (BizServices) context.getBean("bizServices");
}

私のサービスには、次のようにタグ付けされたサービスの Bean があります。

@Service("bizServices")
public class BizServicesImpl implements BizServices { ... }

次のように例外が発生します。

SEVERE: Allocate exception for servlet Spring MVC Dispatcher Servlet
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named     'bizServices' is defined

これは、間違ったアプリケーション コンテキスト サービスを使用しているか、Bean が見つからないことを示しています。Autowire を使用せずに PostConstruct でこの Service クラスを明示的に見つけてロードできますか? サービス クラスをファクトリからロードした場合、ファクトリ クラスを指定できますか?それは xml の Bean 構成エントリになりますか?

再度、感謝します...

4

2 に答える 2

2

@PostConstruct で、新しい ApplicationContext をインスタンス化しています。この新しいインスタンスは、元の ApplicationContext について何も知りません。bizServices へのアクセスを取得する場合は、コントローラーで @Autowire アノテーションを使用して BizServices タイプのフィールドを宣言します。

于 2011-04-17T06:03:35.700 に答える
1

init メソッドでコンテキストを完全にインスタンス化していません。アプリケーション コンテキスト xml のクラスパスの場所を指定して、Bean 定義を手動でロードする必要があります。

GenricApplicationContext javadocから :

使用例:

 GenericApplicationContext ctx = new GenericApplicationContext();
 XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
 xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));  // load your beans
 PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
 propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
 ctx.refresh();

 MyBean myBean = (MyBean) ctx.getBean("myBean");
于 2011-04-17T09:05:02.417 に答える