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

【跟我学spring 4.0 】之第一节-springhello 的创建

2015-12-26 22:52 447 查看


1,什么是spring框架

spring是J2EE应用程序框架,是轻量级的IoC和AOP的容器框架,主要是针对javaBean的生命周期进行管理的轻量级容器,可以单独使用,也可以和Struts框架,ibatis框架等组合使用。


2,架构概述



1)IoC(Inversion of Control)控制反转,对象创建责任的反转,在spring中BeanFacotory是IoC容器的核心接口,负责实例化,定位,配置应用程序中的对象及建立这些对象间的依赖。XmlBeanFacotory实现BeanFactory接口,通过获取xml配置文件数据,组成应用对象及对象间的依赖关系。

spring中有三种注入方式,一种是set注入,一种是接口注入,另一种是构造方法注入。

2)AOP面向切面编程

aop就是纵向的编程,如下图所示,业务1和业务2都需要一个共同的操作,与其往每个业务中都添加同样的代码,不如写一遍代码,让两个业务共同使用这段代码。

spring中面向切面变成的实现有两种方式,一种是动态代理,一种是CGLIB,动态代理必须要提供接口,而CGLIB实现是有继承。

3.eclipse中spring hello world 的创建

引入依赖:

<!-- 引入spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>


4.在classpath路径下,创建springApplication.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"
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" default-autowire="byName" default-lazy-init="true">

<bean id="hello" class="com.zd.runsharing.maven.Hello">
<property name="springhello" value="Spring...."></property>
</bean>

</beans>

5.创建类:Hello.class

package com.zd.runsharing.maven;

public class Hello {
private String springhello;

public Hello() {
super();
System.out.println("constractor.....");
}

public String getSpringhello() {
System.out.println("getSpringhello:"+springhello);
return springhello;
}

public void setSpringhello(String springhello) {
this.springhello = springhello;
}

public void syso(){
System.out.println("水平。。。"+springhello);
}

}


5.主函数:MainTest.class

public class MainTest
{
public static void main( String[] args )
{
//创建hllo这样的一个对象
Hello hello = new Hello();
//为springname属性赋值
hello.setSpringhello("你好");

//1.创建spring IOC容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springApplication.xml");

//2.从IOC容器中获取Bean实例对象
// Hello hello2 = (Hello) applicationContext.getBean("hello");
//3.调用hello方法
// hello2.syso();

}
}

6.运行:eclipse右键 run javaapplication....



好啦,这就是spring的hello world 的快速创建啦。

========================================================================================================================================================================================================================================================================
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: