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>




原文地址:https://www.cnblogs.com/yxysuanfa/p/7115870.html