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(

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

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

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

使用声明 | 英豪名录