您的位置:首页 > 编程语言 > Java开发

建立一个Hello World级别的Spring项目

2016-03-31 16:44 399 查看
package com.sevenhu.domain;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* Created by hu on 2016/3/31.
*/
public class HelloWorld {
private String userName;

//Spring项目中,配置在容器中的类,其属性都必须有setter方法
public void setUserName(String userName) {
this.userName=userName;
}
public void hello(){
System.out.println("Hello: "+userName);
}
public static void main(String[] args){
//1.创建Spring的IOC容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
//2.从容器中获取bean
HelloWorld helloWorld= (HelloWorld) applicationContext.getBean("helloWorld");
System.out.println(helloWorld);
//3.调用方法
helloWorld.hello();
}
}


  Spring的配置文件的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd"> 
<bean id="helloWorld" class="com.sevenhu.domain.HelloWorld">
<property name="userName" value="Spring"></property>
</bean>
</beans>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: