ApplicationContext.getBean()を使用せずにBean参照を取得するという議論がいくつかありますが、そのほとんどは制御の逆転の原則に違反するロジックに基づいています。Springでcontext.getbeanを使用しないようにする方法
context.getBean()を呼び出さずにプロトタイプスコープBeanへの参照を取得する方法はありますか?
ApplicationContext.getBean()を使用せずにBean参照を取得するという議論がいくつかありますが、そのほとんどは制御の逆転の原則に違反するロジックに基づいています。Springでcontext.getbeanを使用しないようにする方法
context.getBean()を呼び出さずにプロトタイプスコープBeanへの参照を取得する方法はありますか?
この種の問題は、ここでより詳細に説明する方法注入を用いて解くことができる:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-method-injection
これはプロトタイプ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();
}
}
を使用する検討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ファイルがありません。 必要に応じて手動設定のコンテキストにアクセスできます。
推奨読書:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory -scopes-sing-prot-interaction –