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

Spring入门Hello World

2014-10-15 10:36 197 查看
这里是关于Hello World的一些基本的操作

Spring 是一个重量级的容器框架,用来配置bean并维护bean之间的关系的框架

想要最初的使用Spring就要学会最基本的配置

<1>引入包,Spring.jar和common-logging.jar这是最基本的两个包

[b]<3>创建一个包com.sun.service,在下面创建一个UserService.java文件[/b]

[b]<!!!!!注意这里没有将配置文件放入web.xml里面是 因为本测试工程压根就不是一个web功能,因为spring框架不一定需要在web下面才能运行和struts不同>[/b]

package com.sun.service;

public class UserService {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
public void sayHello() {
System.out.print("hello----"+this.getName());
}

}


  

<2>创建spring的一个核心文件,applicationContext.xml[相当于hibernate.cfg.xml],一般放在src目录下

<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
<bean id="userService" class="com.sun.service.UserService">
<property name="name">
<value>sunxin</value>
</property>
</bean>

</beans>


  <3>创建一个包com.sun.test,在下面创建一个测试文件Test.java

package com.sun.test;

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

import com.sun.service.UserService;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
//UserService   userService  = new UserService();
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us  = (UserService) ac.getBean("userService");
//us.setName("sunzhiyan");
us.sayHello();

}

}


 

这样就能输出 “hello----sunxin”,完成了Spring的最基本的配置运用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: