spring是一个容器框架,贯穿于web层、service层、DAO层、持久层;
DI和IOC两个概念
第一个spring的例子
1、写一个service类
UserService类
UserService.java
package com.service; public class UserService { private String name; private Info info; public Info getInfo() { return info; } public void setInfo(Info info) { this.info = info; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void say(){ System.out.println("第一个spring"+name); info.showInfo(); } }
被依赖的类Info.java(可选)
Info.java
package com.service; public class Info { private String name; private String email; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void showInfo(){ System.out.println(name+"的邮箱是:"+email+" 年龄是:"+age); } }
2、引入jar包,spring.jar和common Logging.jar(最小要求),写ApplicationContext.xml文件
ApplicationContext.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.0.xsd"> <bean id="userService" class="com.service.UserService"> <property name="name"> <value>邹腾</value> </property> <property name="info" ref="info"/> </bean> <bean id="info" class="com.service.Info"> <property name="name" value="孙中山"/> <property name="age" value="18"/> <property name="email" value="yql@sina.cn"></property> </bean> </beans>
3、测试类Test.java
Test.java
package com.test; import com.service.UserService; import com.util.ApplicationContextUtil; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub /*UserService userservice = new UserService(); userservice.setName("邹腾"); userservice.say();*/ /* ApplicationContext ac= new ClassPathXmlApplicationContext("ApplicationContext.xml"); UserService us=(UserService) ac.getBean("userService"); us.say();*/ /* Info info=new Info(); info.setAge(18); info.setName("邹腾"); info.setEmail("zouteng@sina.cn"); info.showInfo();*/ /* ApplicationContext ac=new ClassPathXmlApplicationContext("ApplicationContext.xml"); Info info=(Info) ac.getBean("info"); info.showInfo();*/ ((UserService)ApplicationContextUtil.getApplicationContext().getBean("userService")).say(); } }
工具类,保证ApplicationContext是单态的
ApplicationContextUtil.java
package com.util; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ApplicationContextUtil { private static ApplicationContext ac=null; private ApplicationContextUtil(){ } static { ac=new ClassPathXmlApplicationContext("ApplicationContext.xml"); } public static ApplicationContext getApplicationContext(){ return ac; } }