Understanding dependency injection in java without relying on a framework. What does it look like in pure java code?

dependency-injection, java, oop, spring

Solution

It would look like this (assuming all beans are prototype scope):

class BeanToBeInjected {
}

class BeanThatNeedsInjection {
    BeanToBeInjected beanToBeInjected;
    public void setBeanToBeInjected(BeanToBeInjected beanToBeInjected) {
        this.beanToBeInjected = beanToBeInjected;
    }
}

class BeanFactory {
    public Object createBean(String id) {
        if("beanThatNeedsInjection".equals(id) {
            BeanThatNeedsInjection beanThatNeedsInjection = new BeanThatNeedsInjection();
            beanThatNeedsInjection.setBeanToBeInjected(new BeanToBeInjected());
            return beanThatNeedsInjection;
        }
        return null;
    }
}

class MyService {
    public void service() {
        BeanThatNeedsInjection beanThatNeedsInjection =
            new BeanFactory().createBean("beanThatNeedsInjection");
    }
}

Of course, enhanced by reflection and other libraries like cglib to create proxy classes on the fly.

Problem

I'm learning about the Spring framework for Java. Its all about dependency injection. Is there blog or some resource or example I can use to understand RAW Dependency injection? In other words, without annotations or xml or any container. What does Dependency Injection look like in pure java code? Thank you in advance!

Original source

Related problems