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:


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.

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
):

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 Oracle
interface.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » Spring and Java Interfaces

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录