Here we are going to see how to configure dependency injection in spring with java . In the below example we have two classes MyClass and Myclass2 .There is a dependency of MyClass2 in Myclass . So lets understand how to inject the depended class into another using Spring.
1 2 3 4 5 6 7 |
public class MyClass { MyClass2 myClass2; MyClass(MyClass2 myClass2){ this.myClass2=myClass2; } } |
1 2 3 4 5 6 |
public class MyClass2 { MyClass2(){ System.out.println("Initializing MyClass2"); } } |
Below is the configuration for injecting MyClass2 into MyClass .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MySpringConf { @Bean public MyClass myClass() { return new MyClass(getClass2()); } @Bean public MyClass2 getClass2() { return new MyClass2(); } } |
1 2 3 4 5 6 7 8 |
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringConfDemo { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MySpringConf.class); MyClass myClass = ctx.getBean(MyClass.class); } } |
Output :
Jun 13, 2017 5:26:43 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 13 17:26:43 IST 2017]; root of context hierarchy
Initializing MyClass2
Here we can notice that MyClass2 is getting injected in MyClass .