本文共 2312 字,大约阅读时间需要 7 分钟。
创建项目 项目名称: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目录,在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 package cn.jbit.spring092601.domain; import java.io.Serializable; /** * 学校 * @author Administrator * */ public class School implements Serializable { private String name;//学校名称 //无参构造函数 public School() { super(); } //带学校名称构造函数 public School(String name) { super(); this.name = name; } //get and set 方法区 public void setName(String name) { this.name = name; } public String getName() { return name; } } 5.在配置文件中编写bean的配置,并注入属性值,也就是我们的DI(Dependency Injection)依赖注入,在这里通过构造函数注入方式实现。配置如下: <?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 id="school" class="cn.jbit.spring092601.domain.School"> <constructor-arg> <value>lisi</value> </constructor-arg> </bean> </beans> 6.测试bean的属性注入 在test目录下测试 包名:cn.jbit.spring092601.domain /** * 构造函数注入 */ @Test public void testConstr(){ BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml")); School school = (School) beanFactory.getBean("school"); System.out.println(school.getName()); }
本文转自 素颜猪 51CTO博客,原文链接:http://blog.51cto.com/suyanzhu/1558485
转载地址:http://cuzfa.baihongyu.com/