I want to write my own simple DI framework.
I want that it perform only this simple case like Spring does:
public interface IWriter {
public void writer(String s);
}
@Service
public class MySpringBeanWithDependency {
private IWriter writer;
@Autowired
public void setWriter(IWriter writer) {
this.writer = writer;
}
public void run() {
String s = "This is my test";
writer.writer(s);
}
}
@Service
public class NiceWriter implements IWriter {
public void writer(String s) {
System.out.println("The string is " + s);
}
}
public class Main extends TestCase {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"META-INF/beans.xml");
MySpringBeanWithDependency test = (MySpringBeanWithDependency) context
.getBean("mySpringBeanWithDependency");
test.run();
}
}
The same case, but mb without an XML-file.
Can somebody explain the concept of this type of frameworks and write some code.
Guice is open source. You can browse the code here:
http://code.google.com/p/google-guice/source/browse/
Spring is also open source. You can download it here:
http://www.springsource.org/download
Browsing through either of these should satisfy the “write some code” part of your question.
EDIT: It seems you are looking for the “magic”. It boils down to reflection. Spring and/or Guice use Java Reflection to find the appropriate setters (or fields) on the class and set the values. That’s it. Everything else is glue to make the whole system work.