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

Spring入门示例

2016-06-23 15:25 525 查看

开发环境

  Spring 4.3.0+Myeclipse2015+JDK1.8

准备阶段:

  1、新建一Spring01项目,然后新建一个lib文件。将下面的添加到lib文件中



  2、将lib文件所有的包导入项目

开发步骤:

  1、新建一个Hello.java的类

package com.proc.bean;

public class Hello {

private String msg;

public void setMsg(String msg) {
this.msg = msg;
}
public void say(){
System.out.println("Hello "+msg);
}
}


  2、在src文件夹下面新建一个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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- id:该实例的名称,class:该实例的类型 -->
<bean id="helloWorld" class="com.proc.bean.Hello">
<!-- 设置属性msg的值为world -->
<property name="msg" value="world"></property>
</bean>
</beans>


  3、代码测试

package com.proc.test;

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

import com.proc.bean.Hello;

public class TestSpring {

@Test
public void test1(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello=(Hello)context.getBean("helloWorld");
hello.say();
}
}


  

  结果输出:

六月 23, 2016 3:23:13 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1637f22: startup date [Thu Jun 23 15:23:13 CST 2016]; root of context hierarchy
六月 23, 2016 3:23:13 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
Hello world
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: