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());
}
}
Spring-装配Bean的3种方式-工厂静态方法方式配置Bean
原创
©著作权归作者所有:来自51CTO博客作者素颜猪的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
struts bean static 静态方法注入
... 我们可以从struts.properties中获取
struts ide apache -
static
static关键字
成员变量 成员方法 静态方法 -
java static调用static java里static
1. 封装1.1 封装的概念 面向对象程序三大特性:封装、继承、多态。而类和对象阶段,主要研究的就是封装特性。何为封装呢?简单来说就是套壳屏蔽细节。 比如:对于电脑这样一个复杂的设备,提供给用户的就只是:开关机、
java static调用static java 开发语言 System 封装