Spring and Java Interfaces

存储架构 2018-03-17 阅读原文

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!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!

您可能感兴趣的

工作一到五年的Java程序员遇到瓶颈应该如何提升自己突破... 具有一到五年开发经验 需要学习内容很多 JVM/分布式/高并发/性能优化/Spring MVC/Spring Boot/Spring Cloud/MyBatis/Netty源码分析等等等 01、透彻理解Tomcat原理手写动静态资源的实现 02、分享能源领域的分布式监测系统架...
What’s new in IntelliJ IDEA 2018.2? The new version of IDE IntelliJ IDEA from JetBrains under the number 2018.2 has introduced several functions for developers using Spring and Spring Bo...
SODA – More Than Just A Table This post begins investigating what goes on behind the scenes to implement a SODA collection in Oracle. Lets dive right in and create a SODA collectio...
Oracle 从 11.2.0.1 升级到 11.2.0.4 版本提示ORA-00119错误解决... Oracle 从 11.2.0.1 升级到 11.2.0.4 版本提示ORA-00119错误解决 1、在线对数据库版本进行升级后,Oracle启动失败。 升级之前好好的,正常都能启动,从11.2.0.1升级到11.2.0.4后,启动报错。 SQL> startup; OR...
Oracle Announce New Support Pricing Structure for ... Oracle have announced a major shift in the way they offer commercial support for Java . The key points are that entry-level support will now be...