1.建立项目
项目名称:spring092601
2.引入spring jar包
commons-logging.jar
junit-4.4.jar
log4j.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
3.添加配置文件
在conf下添加spring的核心配置文件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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
4.建立业务bean
在src目录下建立
包名:cn.jbit.spring092601.domain
/**
* spring入门
* @author Administrator
*
*/
public class HelloSpring implements Serializable {
private String name;
public HelloSpring() {
System.out.println("调用无参构造方法");
}
public HelloSpring(String name) {
super();
this.name = name;
}
public void setName(String name) {
System.out.println("set");
this.name = name;
}
public String getName() {
System.out.println("get");
return name;
}
}
5.在配置文件中编写bean的配置,也就是咱们的IOC(Inversion of Control)控制反转
配置以下:
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- spring入门
控制反转IOC
默认构造方法装配Bean
-->
<bean id="helloSpring" class="cn.jbit.spring092601.domain.HelloSpring">
</bean>
</beans>
6.测试bean的配置
在test目录下测试
包名:cn.jbit.spring092601.domain
public class HelloSpringTest {
/**
* 控制反转方式实现
* IOC方式
*/
@Test
public void testHellpSpring2(){
/*
* 对象由spring建立
*/
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
helloSpring.setName("张三");
System.out.println(helloSpring.getName());
}
}spring