mr.M
mr.M

Reputation: 899

Spring and Java interfaces

While reading some advanced book on developing the enterprise applications, I constantly see the following pattern that could be illustrated by the following example:.

public interface Oracle {
    String defineMeaningOfTheLife();
}
public class BookwormOracle implements Oracle {

    public String defineMeaningOfTheLife() {

        return "Use life, dude!";
    }
}

And the main function:

  public static void main(String[] args) {
XmlBeanDefinitionReader rdr = new XmlBeanDefinitionReader(factory);
        rdr.loadBeanDefinitions(new ClassPathResource(
                "META-INF/spring/xml-bean-factory-config.xml"));

        Oracle oracle = (Oracle) factory.getBean("oracle");
        System.out.println(oracle.defineMeaningOfTheLife());
    }

And the xml config:

<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="oracle" name="wiseworm" class="BookwormOracle" />

As far as I understood, it is not possible to instantiate the interface. But, using Spring framework it seems to me that it is possible to do so. Since, how does the Spring framework manage to do it? From pure Java perspective the code

Oracle oracle = new Oracle();

is rather wrong.

Upvotes: 0

Views: 86

Answers (3)

Bhargav Kumar R
Bhargav Kumar R

Reputation: 2200

This line <bean id="oracle" name="wiseworm" class="BookwormOracle" /> is equal to the below java code.

BookwormOracle oracle = new BookwormOracle();

It just happened to have the name of the variable as oracle in the spring configuration, rather spring actually initializing the concrete class BookwormOracle . Later you are just asking the spring container to get that bean with the name oracle with below line.

Oracle oracle = (Oracle) factory.getBean("oracle");

Upvotes: 0

Selva
Selva

Reputation: 230

You shouldfirst understand about DI(Dependency Injection) and IoC(Inversion of Control) . Please google it .

I would recommend you this article from Martin Fowler on Ioc.

http://martinfowler.com/bliki/InversionOfControl.htmlenter link description here

Thanks

Upvotes: 0

chouk
chouk

Reputation: 289

Spring also needs an implementation of the interface to instanciate the bean and make it available to your application. It is actually what is defined in your context file (xml-bean-factory-config.xml):

<bean id="oracle" name="wiseworm" class="BookwormOracle" />

In the spring context, you define which implementation of the interface Oracle you want to create. When your main method call:

Oracle oracle = (Oracle) factory.getBean("oracle");

it asks to Spring to get the bean with id "oracle" which is an implementation of your Oracleinterface.

Upvotes: 4

Related Questions