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
1).在src目录下创建业务bean
包名:cn.jbit.spring092601.domain
package cn.jbit.spring092601.domain;
import java.io.Serializable;
/**
* 学生类
* @author Administrator
*
*/
public class Student implements Serializable {
//学生姓名
private String studentName;
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentName() {
return studentName;
}
}
2).在src目录下创建工厂Bean
包名:cn.jbit.spring092601.factory
package cn.jbit.spring092601.factory;
import cn.jbit.spring092601.domain.Student;
/**
* 学生工厂类
* @author Administrator
*
*/
public class StudentFactory {
public static Student getStudent(){
return new Student();
}
}
5.在配置文件中编写bean的配置,并注入属性值
配置如下:
<?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">
<!--
工厂静态方法方式 装配Bean
-->
<bean id="studentFactory" class="cn.jbit.spring092601.factory.StudentFactory" factory-method="getStudent">
<property name="studentName">
<value>小明</value>
</property>
</bean>
</beans>
6.测试bean的装配
在test目录下测试
包名:cn.jbit.spring092601.domain
public class HelloSpringTest {
/**
* 工厂静态方法方式装配Bean
*/
@Test
public void testFactory(){
/*
*
* 对象由spring创建,调用工厂中的静态方法来创建Bean
*/
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
Student student = (Student) beanFactory.getBean("studentFactory");
System.out.println(student.getStudentName());
}
}
转载于:https://blog.51cto.com/suyanzhu/1558450