本文主要初步介绍spring框架的搭建和认识
首先,引入spring.jar和commons-logging.jar两个包,然后创建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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="userService" class="com.service.UserService">
<property name="name">
<value>siege</value>
</property>
<property name="byeService" ref="byeService"></property>
</bean>
<bean id="byeService" class="com.service.ByeService">
<property name="name">
<value>xuhaiyue</value>
</property>
</bean>
</beans>
然后编写测试类:
先创建获取ApplicationContext对象的公共方法:
package com.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class ApplicationContextUtil {
private static ApplicationContext ac=null;
ApplicationContextUtil(){
}
static {
ac=new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static ApplicationContext getApplicationContext(){
return ac;
}
}
然后编写ByeService.java文件
package com.service;
public class ByeService {
private String name;
public void sayBye(){
System.out.println("bye,"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接着 编写 UserService.java文件
package com.service;
public class UserService {
private String name;
private ByeService byeService;
public void hello(){
System.out.println(name+",hello");
byeService.sayBye();
}
public ByeService getByeService() {
return byeService;
}
public void setByeService(ByeService byeService) {
this.byeService = byeService;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
最后编写测试类:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.ByeService;
import com.service.UserService;
import com.util.ApplicationContextUtil;
public class Test {
public static void main(String[] args) {
/*ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us=(UserService) ac.getBean("userService");
us.hello();
ByeService bs=(ByeService) ac.getBean("byeService");
bs.sayBye();*/
UserService us=(UserService) ApplicationContextUtil.getApplicationContext().getBean("userService");
us.hello();
}
}
总结: