1.Spring4.0---输出HelloWorld

一.Spring是什么?

       1.Spring 是一个开源框架.

2.Spring 为简化企业级应用开发而生. 使用 Spring 可以使简单的 JavaBean 实现以前只有 EJB 才能实现的功能..

3.Spring 是一个 IOC(DI) 和 AOP 容器框架.

具体描述Sping:

 1.轻量级:Spring是非侵入式的,基于Spring开发的应用中的对象可以不依赖于Spring的API
2.依赖注入:(DI—dependencyinjection,IO)(后面介绍)
3.面向切面编程(AOP---aspect oriented programming)
4.容器:Spring 是一个容器,因为它包含并且管理应用对象的生命周期
4.框架:Spring实现了使用简单的组件配置组合成一个复杂的应用,在Spring中可以使用xml和Java注解组合这些对象
5.一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring自身也提供了展现层的SpringMVC和持久层的Spring JDBC)
二.搭建Spring开发环境
(1)把jar包加入到工程的lib文件夹下

(2)Spring的配置文件:一个典型的Spring项目需要创建一个或多个Bean配置文件,这些配置文件用于在Spring IOC容器里配置Bean,Bean的配置文件可以你放在classpath下,也可以放到其他目录下
(3)代码实现:
1.先写一个JavaBean,HelloWorld.java

package com.example.spring.beans;

public class HelloWorld {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	public void hello(){
		System.out.println("hello:"+this.name);
	}

}
2.在src目录下创建配置文件applicationContext.xml

每一个 <bean></bean>代表一个对象,id是唯一标识,name代表属性名,value代表属性值,这是属性注入,以后还会再说另外一种注入方式,叫构造注入

<?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:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	<!-- 配置bean -->
	<bean id="h" class="com.example.spring.beans.HelloWorld">
		<property name="name" value="Spring"></property> 
	</bean><pre name="code" class="java"></beans>
 
3.编写测试类 

package com.example.spring.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext
<span style="font-family: Arial, Helvetica, sans-serif;">public class Main {</span>
	public static void main(String[] args) {
//		HelloWorld helloWorld=new HelloWorld();
//		helloWorld.setName("hello world!");
		
		//创建Spring的IOC容器,作用:调用构造方法进行初始化,并调用set方法为参数赋值
		//ApplicationContext 代表IOC容器(是个接口)
		//ClassPathXmlApplicationContext:ApplicationContext的子接口
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		
		//从容器中获取Bean
		//利用Id定位到IOC容器中的Bean
		HelloWorld helloWorld=(HelloWorld)ctx.getBean("h");
		System.out.println(helloWorld)
		
		//调用hello方法
		helloWorld.hello();
		
	}
}

点击下载源码



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值