IoC 容器基本实例

参考地址:http://sishuok.com/forum/blogPost/list/2428.html


建立maven项目,在pom.xm中添加依赖包

        


    org.springframework
    spring-context
    4.0.0.Release



    org.springframework
    spring-core
    4.0.0.Release



    org.springframework
    spring-beans
    4.0.0.Release



    org.springframework
    spring-jdbc
    4.0.0.Release




    org.springframework
    spring-context-support
    4.0.0.Release




    org.springframework
    spring-jms
    4.0.0.RELEASE

HelloApi

package com.eastcom.first.spark.data.spring;

public interface HelloApi {

	public void sayHello();

}

HelloImpl

package com.eastcom.first.spark.data.spring;

public class HelloImpl implements HelloApi {

	@Override
	public void sayHello() {
		// TODO Auto-generated method stub

		System.out.println("this is a spring hello world!");

	}

}

HelloTest

package com.eastcom.first.spark.data.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloTest {

	public static void main(String[] args) {

		testHelloWorld();

	}

	public static void testHelloWorld() {

		String confDir = "file:D:/newworkspace/my-study-spark/config/helloworld.xml";
		// 1、读取配置文件实例化一个IoC容器
		ApplicationContext context = new ClassPathXmlApplicationContext(confDir);
		// 2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
		HelloApi helloApi = context.getBean("hello", HelloApi.class);
		// 3、执行业务逻辑
		helloApi.sayHello();
	}
}


你可能感兴趣的:(spring)