2016-03-31 7 views
2

具体的には、構成クラスをインスタンス化し、それらを含めて構成クラスを共有できるようにしたいと考えています。あなたは通常、これを実行する場所:Springの@Configurationアノテーションをプログラムで設定するにはどうすればよいですか?

@Configuration 
@Import({SharedConfiguration.class}) 
public class MyAppContext extends WebMvcConfigurerAdapter { 
    //stuff 
} 

@Configuration 
@ComponentScan("com.example") 
public class SharedConfiguration { 
    //stuff 
} 

は、私はこれをやりたい:

@Configuration 
public class MyAppContext extends WebMvcConfigurerAdapter { 
    public SharedConfiguration sharedConfig(){ 
    return new SharedConfiguration("com.example"); 
    } 

    //stuff 
} 

@Configuration 
public class SharedConfiguration { 
    public SharedConfiguration(String package){ 
    //tell Spring to scan package 
    } 
} 

この理由は、私がどのようなパッケージへのスキャンをやって共有コンポーネントを伝えることができる必要があるということです見る。また、それはで使用されているもののプロジェクトに応じて異なるであろう

EDIT:。

いくつかの追加のコンテキストを提供するために、私は私たちの外部のコンフィギュレーションを使用してHibernateとEHCacheなどを設定するための一般的な用途の設定をしようとしていますいくつかのプロジェクトで使用できるプロバイダです。私は確かにこれを行うために他の方法にオープンですが、これは私にとって最も論理的な道のように思えました。私は、春に何か〜があると確信しています。「ここで、春があなたを初期化するとき、この道をスキャンしてください!注釈にハードコーディングするのではなく、

+0

XY問題のような音です。詳細は参考になります。特に、異なる状況下で異なるパッケージをスキャンする目的は何ですか?これは、プロファイル、条件、自動設定の場合のように聞こえます。 – chrylis

+0

@chrylisもう少し明確にするために質問を更新しました。確かにXYの問題かもしれませんが、私はプログラム的なやり方で物事をしようとしていますし、Springは決して非常にプログラマチックではありません。 – monitorjbl

+0

あなたは、自動設定をしたいと思っています。基本的にSPIを使って '@Configuration'クラスを見つけ、それをコンテキストにインポートします。 – chrylis

答えて

0

この場合、プロパティソースを利用できます。

@Configuration 
@ComponentScan("${packages}") 
public class SharedConfiguration {} 

その他の参照クラス - ComponentScan春の式言語を使用して

@RunWith(SpringRunner.class) 
@ContextConfiguration 
public class MyAppContextTest { 

    @Autowired 
    ApplicationContext context; 

    @BeforeClass 
    public static void beforeClass() { 
     // use a system property to configure the component scan location of the SharedConfiguration 
     // where the "ExampleBean" lives 
     System.setProperty("packages", "net.savantly.other.packages"); 
    } 

    @Test 
    public void ensureExampleBeanExists() { 
     // throws exception if it doesnt exist 
     context.getBean(ExampleBean.class); 
    } 


    @Configuration 
    @Import(MyAppContext.class) 
    static class TestContext { 

    } 
} 

- テストケースで
は、私は春のプロパティソースの設定によってピックアップされたシステムプロパティを設定しています -

@Configuration 
@Import(SharedConfiguration.class) 
public class MyAppContext extends WebMvcConfigurerAdapter { 

    @Autowired 
    SharedConfiguration sharedConfig; 

    //stuff 
} 

@Service 
public class ExampleBean { 

} 
関連する問題