spring helloworld

来源:互联网 发布:jquery.fly.js用法 编辑:程序博客网 时间:2024/06/06 03:44

spring 是什么?

IOC和AOP

开源框架

可以原本需要使用EJB繁琐的配置变的简单


spring优点?

轻量级:spring是非侵入性的,基于spring开发的应用中的对象不依赖于spring的api

依赖注入:(DI,IOC)

面向切面编程(AOP)

容器:spring是一个容器,因为它包含并且管理应用对象的生命周期

框架:spring实现了使用简单的组件配置合成一个复杂应用,在spring中可以使用xml和java注解组合这些对象

一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上spring自身也提供了展现层的springmvc和持久层的spring jdbc)

 

spring模块



安装插件(spring tool suite)

spring tool suite是一个eclipse插件,利用该插件可以更方便的在eclipse平台上开发基于spring的应用

插件下载地址:http://spring.io/tools/sts/all


下载插件,安装时注意:只需要安装以spring IDE结尾的模块即可


搭建spring开发环境

导入如下jar包:


注意:commons-logging-1.1.3.jar是spring额外需要依赖的日志包。下载地址:

http://commons.apache.org/proper/commons-logging/

导入这些包并加入build path路径


创建配置文件

spring配置文件:一个典型的spring项目需要创建一个或多个Bean配置文件,这些配置文件用于在spring IOC容器里配置Bean,Bean配置文件可以放在classpath下,也可以放在其他目录下

 





实例代码:

目录结构


HelloWorld.java

package com.coslay.beans;public class HelloWorld {private String name;public void setName(String name){System.out.println("setName: ");this.name = name;}public void hello(){System.out.println("hello: "+name);}public HelloWorld(){System.out.println("HelloWorld's Constructor...");}}


Main.java

package com.coslay.spring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.coslay.beans.HelloWorld;public class Main {public static void main(String[] args) {////创建HelloWorld的一个对象//HelloWorld helloWorld = new HelloWorld();////为name属性赋值//helloWorld.setName("yyz");//      使用spring以后,这两步可交给spring完成//1.创建spirng的IOC对象ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//创建容器的时候会调用所有bean对象的构造器,并为bean注入(赋值)//2.从IOC容器中获取Bean实例HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");//调用hello方法helloWorld.hello();}}



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"><!-- 配置bean --><bean id="helloWorld" class="com.coslay.beans.HelloWorld"><property name="name" value="yyz"></property></bean></beans>




0 0
原创粉丝点击