package main.java.com.mycompany.bean;
/**
* Bean
* @author Administrator
*
*/
public class HelloWorld {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
* 输出信息
*/
public void printHello(){
System.out.println("Spring 4 "+this.name);
}
}<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- id:取的是一个唯一标识名 class:对应的是HelloWorld的完整类名(包名+类名的组合) property:表示HelloWorld这个类中有一个属性叫name,并且对这个属性进行了赋值操作,值为yunshuo --> <bean id="helloWorldBean" class="main.java.com.mycompany.bean.HelloWorld"> <property name="name" value="yunshuo" /> </bean> </beans>
12.HelloWorldTest类中的内容如下
package main.java.com.mycompany.bean;
import main.java.com.mycompany.bean.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldTest {
@Test
public void helloWorldTest(){
//获取配置文件上下文
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过上下文获取bean对象,并转换为具体的HelloWorld类
HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorldBean");
//调用HelloWorld类中的打印信息方法
helloWorld.printHello();
}
}本文出自 “素颜” 博客,请务必保留此出处http://suyanzhu.blog.51cto.com/8050189/1908656
原文地址:http://suyanzhu.blog.51cto.com/8050189/1908656