本节重点讲述:IOC中bean的概念,以及一个简单Hello word的实例。
1. bean容器概念
上一节我们讲到IOC是管理我们应用程序对象的一个容器,我们把自己的对象放进去之后就另外取了一个名字,我这个名字就是豆子(Bean),Bean就是Spring容器初始化、装配以及管理的对象,可以理解为对象在IOC里面的名字。例如我们平常创建的一个对象叫做Student,在Spring中我们创建的一个对象就叫Bean。
那么问题就来了,我们平常根据不同的对象名称来区分不同的对象比如Student,Person,Spring中全部都叫Bean那怎么区分?
Spring解决的办法就是在Bean中标明一个id属性,来表明我这个Bean与别的Bean的不同之处,问题就解决了。
2. 简单实例
概念到此就结束了,现在来介绍一个简单的例子。
配置Spring的过程自行百度.....
我们直接从构建一个java工程开始,在构建一个java 工程之后,我们首先来定义一个Interface:
package com.test.spring;
public interface HelloApi {
public void sayHello();
}
然后,我们来实现这个接口中的函数:
package com.test.spring;
public class HelloImpl implements HelloApi{
@Override
public void sayHello() {
System.out.println("Hello world!");
}
}
接口和实现方法都已经弄好了,现在我们开始对这个工程就行配置,在本工程下创建一个helloworld.xml文件,内容为:
<?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="com.test.spring.HelloImpl"></bean>
</beans>
这里面的重点就是:
<bean id="hello" class="com.test.spring.HelloImpl"></bean>
然后我们写一个test测试类:
package com.test.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void testHello() {
//1.读取配置文件,实例化一个IOC容器
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("src/main/resources/helloworld.xml");
//2.从容器中获取bean
HelloApi helloApi = context.getBean("hello",HelloImpl.class);
//3.执行业务逻辑
helloApi.sayHello();
}
}
执行以下:得到
Hello world!
至此一个简单的hello world就完成了,,待续,,