代码非常简单。如果缺少jar包将导致报错。
需要5个spring jar包和1个logging jar,否则报错。
org.springframework.asm.jar
org.springframework.core.jar
org.springframework.beans.jar
org.springframework.context.jar
org.springframework.expression.jar
定义一个接口,一个实现类。java project项目。
package ioc; public interface HelloApi { public void sayHello(); }
package ioc; public class Hello implements HelloApi{ @Override public void sayHello() { System.out.println("Hello World!"); } }
package ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml"); HelloApi helloApi = context.getBean("hello", HelloApi.class); helloApi.sayHello(); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- id 表示你这个组件的名字,class表示组件类 --> <bean id="hello" class="ioc.Hello"></bean> </beans>
不清楚如何找到该xml文件。
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");