Spring之HelloWorld
搭建环境(参考:http://huangminwen.iteye.com/admin/blogs/1873922)
有如下接口:
package org.spring.service;
public interface PersonService {
public void showMessage();
}
实现类:
package org.spring.service.impl;
import org.spring.service.PersonService;
public class PersonServiceBean implements PersonService {
public void showMessage() {
System.out.println("Hello Spring World!");
}
}
现在我们不想在代码中直接实例化PersonServiceBean类,想把它交给Spring容器管理,这时我们就需要在spring.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="personServiceBean" class="org.spring.service.impl.PersonServiceBean" /> </beans>
在编写spring配置文件时,如果没有联网,则不能出现帮助信息,解决方法:
Window->Preferences->MyEclipse->Files and Editors->XML-> XML Catalog
点"add",在出现的窗口中的Key Type中选择URI,在location中选"File system",然后在spring解压目录, 的 dist/resources目录中选择spring-beans-2.5.xsd,回到设置窗口的时候,一定要把窗口中的Key Type改为Schema location,Key改为 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
beans.xml中的<bean>元素是用于配置我们要交给Spring管理的bean类,通过Bean中的id属性可以获得该Bean,该值不能包含特殊字符,Bean也可由name属性获得,与id属性所不同的是name属性可以包含特殊字符,如:(/spring/spring)
class属性:指定要交给Spring管理的Bean类,当spring容器启动后,因为spring容器可以管理bean对象的创建,销毁等生命周期,所以我们只需从容器直接获取Bean对象就行,而不用编写一句代码来创建bean对象。
测试类:
package org.spring.junit;
import org.junit.Test;
import org.spring.service.PersonService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");
PersonService personService = (PersonService) ctx
.getBean("personServiceBean");
personService.showMessage();
}
}
控制台打印信息:
工程目录结构图: