2017-02-28 136 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