2017-02-28 134 views
0

關於不使用ApplicationContext.getBean()來獲取bean引用有幾個爭論,其中大多數是基於違反控制反轉原理的邏輯。如何避免在spring中使用context.getbean

有沒有一種方法可以在不調用context.getBean()的情況下獲取原型scoped bean的引用?

+0

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory -scopes星-PROT互動 –

回答

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