2016-07-08 13 views
0

new()への呼び出しによって作成されるインスタンスでジェネリックDAOサービスをAutowireできるようにしたいのです...私のJavaコードで。私は@configurableがThis spring docを見る正しい方法だと理解しました。だからここ@Configurableクラスで@Autowiredは動作しません

は、私は、メイン設定クラスはそのように見えるこの

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = { xxx.MainConfig.class }) 
@ActiveProfiles({ "database-test", "classpath" }) 
public class DynVdynOperationsImplTest { 

    @Test 
    public void testSend() { 
    underTest = new DynVdynOperationsImpl(); 
    underTest.sendVdyn("0254", null, null); 
    ... } 

のように見える春のテストとJUnitテストでそれを使用したい私のクラスのコード

@Configurable(dependencyCheck=true) 
public class DynVdynOperationsImpl implements DynVdynOperations { 

    @Autowired 
    private DynVdynInDbDao vdynDao; 

ある

@Configuration 
@EnableSpringConfigured 
@ComponentScan(basePackages = {xxx }) 
public class MainConfig { 
... 
    @Bean 
    @Scope("prototype") 
    public DynVdynOperations vdynOperations() { 
     return new DynVdynOperationsImpl(); 
    } 

テストを実行すると、未テストのvdynDaoプロパティは適切に自動配線されずに残りますヌル。 this similar questionを見ると、自分の設定でAspectJに関して不足しているかもしれません。

簡単に動作させる方法はありますか?つまり、私は自分のコードにオブジェクトを作成するときに自分自身を注入するのに比べて、飛行機を殺すためにハンマーを使用するような気がしないのですか? @Serviceオブジェクト内の自分のコードから直接Spring Beanファクトリを呼び出すことができますか?

答えて

0

ここでは、これを行うには最高の簡単な方法があるようです。 AspectJの使用の複雑さを避けます。

構成クラスは問題ありません。 @Scope("prototype")でBeanを宣言すると、SpringにこのクラスのBeanを取得するように要求するたびに、新しいインスタンスが作成されます。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = { xxx.MainConfig.class }) 
@ActiveProfiles({ "database-test", "classpath" }) 
public class DynVdynOperationsImplTest { 

    @Autowired 
    ApplicationContext context; 

    @Test 
    public void testSend() { 
    underTest = context.getBean(DynVdynOperations.class); 
    underTest.sendVdyn("0254", null, null); 
    ... } 
:テストクラスで

、アプリケーション・コンテキストを使用してBeanを生成するスプリングコンテナを尋ねます

0

DynVdynOperationsImplのクラス定義に@Scope( "プロトタイプ")を入れてみてください。

また、代わりに「新DynVdynOperationsImpl」の、私はあなたが豆(すなわち「DynVdynOperations」)を指名する必要があると思うし、次に使用: applicationContext.getBean(「DynVdynOperations」)、それの新しいインスタンスを作成します。 getBeanを使用すると、見つかった配線をSpringが処理するよう指示します。

関連する問題