J2EE系列之Spring4学习笔记(一)--Spring介绍

关于Spring的介绍参考百度百科:

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。

官方网站:http://spring.io/
最新开发包及文档下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/


Spring的核心思想:IOC 控制反转;AOP 面向切面;

一、Spring之HelloWorld实现

1.新建一个JavaProject:Spring401;

2.添加jar包:下载Spring开发包,并解压缩:这里使用的是4.0.6版本


libs里面是Spring的所有jar包,这些jar包包括文档和源码。虽然里面有很多jar包,最常用的核心包有一下几个:


在工程根目录下新建一个spring文件夹,把这几个核心包复制进去并添加到工程中:


Spring功能之一是能够管理bean,管理实例,以单例形式管理。

3.新建HelloWorld类:

package com.test.service;

public class HelloWorld {

	public void say(){
		System.out.println("你好,Spring4");
	}
}

4.添加spring的配置文件beans.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">


  
</beans>

下面使用Spring的方式新建一个HelloWorld类的对象:

<?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 id="helloWorld" class="com.test.service.HelloWorld"></bean>
  
</beans>

这样就通过Spring的方式新建了一个HelloWorld类的对象,通过id属性就能够使用这个对象。

新建一个测试方法:

package com.test.test;

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

import com.test.service.HelloWorld;

public class Test {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
		HelloWorld hw = (HelloWorld) ac.getBean("helloWorld");
		
		hw.say();
	}
}

这里首先通过ClassPathXmlApplicationContext("beans.xml")来加载Spring的配置文件,返回的是一个ApplicationContext的对象。接着通过这个对象的getBean方法来获取Spring定义的对象。


这里是Spring的一个管理实例对象的功能。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值