Spring4--Hello World实例

来源:互联网 发布:java软件开发笔试题 编辑:程序博客网 时间:2024/04/28 06:46

1.首先,导入相应的Spring jar 包:

除了引入Spring required包之外,还要多引入commons-logging.jar(Struts2中的一个jar包);


2.创建一个HelloWorld 的bean :

package com.spring.bean;public class HelloWorld {private String name;public void setName(String name){this.name = name;}public void hello(){System.out.println("hello:"+name);}}

3.编写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:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd" >               <bean id="helloWorld" class="com.spring.bean.HelloWorld">        <property name="name" value="Spring"></property>        </bean></beans>        


4.创建类Main实现相应的功能:


package com.spring.bean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {/*//创建一个HelloWorld对象HelloWorld helloWorld = new HelloWorld();//为name属性附值helloWorld.setName("wanwan");*///1.创建Spring的IOC容器对象ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//2.从IOC容器中获取Bean实列HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");//调用类的方法helloWorld.hello();}}


0 0
原创粉丝点击