如何避免在spring中使用context.getbean

时间:2017-02-28 16:52:37

标签: spring

有几个关于不使用ApplicationContext.getBean()来获取bean引用的参数,其中大多数都是基于它违反控制反转原理的逻辑。

有没有办法在不调用context.getBean()的情况下获取对原型范围bean的引用?

3 个答案:

答案 0 :(得分:0)

这种类型的问题可以使用方法注入来解决,这里有更详细的描述:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-method-injection

答案 1 :(得分: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();
    } 
}

答案 2 :(得分: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