一、Spring入门示例

1.搭建Spring环境
下载jar
http://maven.springframework.org/release/org/springframework/spring/
spring-framework-4.3.9.RELEASE-dist.zip
开发spring至少需要使用的jar(5个+1个):
spring-aop.jar 开发AOP特性时需要的JAR
spring-beans.jar 处理Bean的jar
spring-context.jar 处理spring上下文的jar
spring-core.jar spring核心jar
spring-expression.jar spring表达式
三方提供的日志jar
commons-logging.jar 日志

2.配置文件applicationContext.xml,添加相应的bean标签
(为了编写时有一些提示、自动生成一些配置信息: 直接下载sts工具(相当于一个集合了Spring tool suite的Eclipse): https://spring.io/tools/sts/ )

//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 id="student" class="org.lanqiao.entity.Student">//id代表标识;class所代表的类的全类名	
		<property name="stuNo" value="2"></property>//name:属性名;value:属性值
		<property name="stuName" value="ls"></property>
		<property name="stuAge" value="24"></property>
	</bean>

</beans>
//Student
package org.lanqiao.entity;

import org.lanqiao.factory.CourseFactory;
import org.lanqiao.newinstance.HtmlCourse;
import org.lanqiao.newinstance.ICourse;
import org.lanqiao.newinstance.JavaCourse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Student {
	private int stuNo ; 
	private String stuName ; 
	private int stuAge ;
	public int getStuNo() {
		return stuNo;
	}
	public void setStuNo(int stuNo) {
		this.stuNo = stuNo;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public int getStuAge() {
		return stuAge;
	}
	public void setStuAge(int stuAge) {
		this.stuAge = stuAge;
	}
	
	@Override
	public String toString() {
		return this.stuNo+","+this.stuName+","+this.stuAge;
	}
}

3.测试类Test

public class Test {	
	public static void springIoc() {
		
		ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml") ;//Spring上下文对象:conext
		Student student = (Student)conext.getBean("student") ;//执行从springIOC容器中获取一个 id为student的对象
		System.out.println(student);
	}
	public static void main(String[] args) {

		springIoc();
	}
}
发布了16 篇原创文章 · 获赞 0 · 访问量 230

猜你喜欢

转载自blog.csdn.net/BTLA_2020/article/details/105184041