spring helloworld

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值