私はSpring IOCのコンセプトを始めたばかりです。インターネットで見つかったほとんどの例では、コードを使用してオブジェクトを取得することがよくあります。
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello = (Hello) appContext.getBean("hello");
stackoverflow のこれらの質問1および2からの参照として。私は、悪い習慣と見なされるコードで appContext.getBean("hello") を使用する必要はないと推測しました。また、推奨されなくなりました。私の推論が間違っている場合は、ここで訂正してください。
それを考慮して、それに応じてプロジェクトに変更を加えました。これが私のapplicationContext.xmlです
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="utilClassRef" class="org.hd.derbyops.DUtils" lazy-init="false" />
<bean id="appContext" class="org.hd.derbyops.ContextProvider" lazy-init="false">
<property name="utils" ref="utilClassRef" />
</bean>
</beans>
私のcontextProviderクラスコード
public class ContextProvider implements ApplicationContextAware {
private static ApplicationContext ctx;
/**
* Objects as properties
*/
private static DUtils utils;
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
public static DUtils getUtils() {
return utils;
}
public void setUtils(DUtils dUtilsRef) {
utils = dUtilsRef;
}
}
たとえば、org.hd.derbyops.DUtils に依存するクラス A を考えてみましょう。次のコード行を使用しています
ContextProvider.getUtils();
クラスAでDUtilsオブジェクトを取得するため ApplicationContext.getBean()
、コード内のどこでも使用できなくなります。
10 個のクラスがあり、クラス A がそれらすべてに依存しており、そのオブジェクトが を使用せずに作成およびアクセスされるとしますApplicationContext.getBean()
。その場合も、上記のように、ContextProvider クラスのプロパティを作成し、その後にそのプロパティのセッターとゲッターを作成することを考えています。ここで、inget<PropertyName>
は静的です。そのため、このように、オブジェクトが必要な場所ならどこでも使用できます
ContextProvider.get<PropertyName>;
これが私の簡単な質問です。まず、私のアプローチは正しいですか?もしそうなら、起動時にすべての Bean をロードすると、パフォーマンス キラーになりませんか? getBean を少なくとも 2 回以上呼び出すことなく、アプリケーションでそれを行うにはどうすればよいでしょうか?
Web アプリケーションを設計しApplicationContext.getBean()
、コードを使用せずに Spring IOC を実装する場合。どうやってそれをしますか?
注:上記でタグ付けされた他の質問を参照してください。
ApplicationContext.getBean() の呼び出しは制御の反転ではありません!