2017-02-28 6 views
0

ApplicationContext.getBean()を使用せずにBean参照を取得するという議論がいくつかありますが、そのほとんどは制御の逆転の原則に違反するロジックに基づいています。Springでcontext.getbeanを使用しないようにする方法

context.getBean()を呼び出さずにプロトタイプスコープBeanへの参照を取得する方法はありますか?

+0

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory -scopes-sing-prot-interaction –

答えて

0

これはプロトタイプBeanを作成する最も一般的なアプローチである:

abstract class MyService { 
    void doSome() { 
     OtherService otherService = getOtherService(); 
    } 
    abstract OtherService getOtherService(); 
} 

@Configuration 
class Config {  
    @Bean 
    public MyService myService() { 
     return new MyService() { 
      OtherService getOtherService() { 
       return otherService(); 
      } 
     } 
    } 
    @Bean 
    @Scope("prototype") 
    public OtherService otherService() { 
     return new OtherService(); 
    } 
} 
0

を使用する検討Spring Boot !あなたはこのような何かを行うことができるよりも

...

ランナー:

@SpringBootApplication 
public class Runner{ 
    public static void main(String[] args) { 
     SpringApplication.run(Runner.class, args); 
    } 
} 

いくつかのコントローラー:

@Controller 
public class MyController { 

    // Spring Boot injecting beans through @Autowired annotation 
    @Autowired 
    @Qualifier("CoolFeature") // Use Qualifier annotation to mark a class, if for example 
            // you have more than one concreate class with differant implementations of some interface. 
    private CoolFeature myFeature; 

    public void testFeature(){ 
      myFeature.doStuff(); 
    } 
} 

いくつかのクールな機能:

@Component("CoolFeature") // To identify with Qualifier 
public class CoolFeature{ 

    @Autowired 
    private SomeOtherBean utilityBean; 

    public void doStuff(){ 
     // use utilityBean in some way 
    } 
} 

処理するXMLファイルがありません。 必要に応じて手動設定のコンテキストにアクセスできます。

推奨読書:

Spring Boot Reference

Pro Spring Boot

関連する問題