Spring Ders09 - Dependency Injection Alternatifleri | Lookup Method
Dependency Injection (Bağımlılık enjektesi) na alternatif olarak bir kaç yöntem bulunur. Bu yöntemler
- Lookup Method
- AutoWiring
- Annotation-driven AutoWiring
Lookup Method
Method Injection olarak da anılır. Singleton bean prototype bean üzerinde bağımlığa sahipse, lookup metot kullanılmadığında getBean ile bean kaç kez çağrılırsa çağrılsın singleton bean üzerinden hep aynı prototype bean örneğine erişilir. Lookup metot kullanıldığında ise yeni bir bean örneğine erişilmiş olur.<lookup-method name="getB" bean="b"/> </bean> <bean id="b" class="test.B" scope="prototype"/> |
... public abstract B getB(); ... } public class B{ ... public B getB(){ return this; } ... } |
Aşağıda örnek bir program verilmiştir.
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String args[]){ ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); A a=(A)context.getBean("a"); B b1=a.getB(); B b2=a.getB(); if(b1==b2){ System.out.println("b1 ve b2 aynı örnekler."); } else{ System.out.println("b1 ve b2 farklı örnekler."); } } }
A.java
package test; public abstract class A { public A() { System.out.println("A örneği oluşturuldu. (singleton bean)"); } public abstract B getB(); }
B.java
package test; public class B { public B() { System.out.println("B örneği oluşturuldu. (protoype bean)"); } public B getB() { return this; } }
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.xsd"> <bean id="a" class="test.A" scope="singleton"> <lookup-method name="getB" bean="b" /> </bean> <bean id="b" class="test.B" scope="prototype"/> </beans>
Yorumlar
Yorum Gönder