命名空间p方式的属性注入
---------------------siwuxie095
命名空间 p 方式的属性注入
命名空间 p 方式的属性注入是 Spring 2.x 版本后提供的方式
1、编写一个普通类
Book.java:
|
package com.siwuxie095.property;
public class Book {
private String bookName;
public void setBookName(String bookName) { this.bookName = bookName; }
public void print() { System.out.println("Book:"+bookName); } } |
2、在配置文件中注入属性
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"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 在 beans 标签中引入 p 命名空间: xmlns:p="http://www.springframework.org/schema/p" -->
<!-- 命名空间 p 方式的属性注入 --> <bean id="book" class="com.siwuxie095.property.Book" p:bookName="十万个为什么"></bean>
</beans> |
3、编写一个测试类
TestProperty.java:
|
package com.siwuxie095.property;
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestProperty {
/** * 手动加上 @Test 以进行单元测试(将自动导入 JUnit 4 的 jar 包) * * 选中方法名,右键->Run As->JUint Test */ @Test public void testProperty() { // (1) 加载 Spring 的核心配置文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
// (2) 得到核心配置文件中创建的对象(获取 Bean 实例) Book book=(Book) context.getBean("book");
book.print(); } } |
【made by siwuxie095】
posted on 2017-08-21 09:53 siwuxie095 阅读(401) 评论(0) 收藏 举报

浙公网安备 33010602011771号