星生

导航

小试牛刀 spring的HelloWorld

先导入包:

commons-logging-1.1.1.jar  : spring依赖的包;

spring-beans-4.0.0.RELEASE.jar;

spring-context-4.0.0.RELEASE.jar;

spring-core-4.0.0.RELEASE.jar;

spring-expression-4.0.0.RELEASE.jar;

 

 1 package com.model;
 2 
 3 public class HelloWorld {
 4 
 5     private String username;
 6 
 7     public void setUsername(String username) {
 8         this.username = username;
 9     }
10     
11     public void hello(){
12         System.out.println("hello:"+username);
13     }
14     
15 }
View Code
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <bean id="hello" class="com.model.HelloWorld">
 7         <property name="username" value="spring4"></property>
 8     </bean>
 9 
10 
11 </beans>
 1 package com.model;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Main {
 7 
 8     public static void main(String[] args) {
 9         //获取spring的IOC容器
10         ApplicationContext ac = new ClassPathXmlApplicationContext("hello.xml");
11         
12         //从容器中获取bean;hello对于xml文件中bean的id
13         HelloWorld helloWorld = (HelloWorld) ac.getBean("hello");
14         System.out.println(helloWorld);
15         //调用方法
16         helloWorld.hello();
17     }
18     
19 }

打印结果:

十二月 06, 2014 9:51:47 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1642bd6: startup date [Sat Dec 06 09:51:47 CST 2014]; root of context hierarchy
十二月 06, 2014 9:51:47 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [hello.xml]
com.model.HelloWorld@154ab89
hello:spring4

posted on 2014-12-06 09:57  Q星ZX  阅读(140)  评论(0编辑  收藏  举报