SSH之spring框架 之第一个spring程序

前言:

Stuuts的意义:为了解决MVC设计模式采用的一种框架
Hibernate是为了解决OPM的映射,即实体类与数据库表之间映射,并对数据库操作进行封装
Spring 涉及三层架构中的每一层

Spring是web开发的接口使用
IOC是spring的核心
Spring 可以将三层架构囊括
Spring 将其他的联系在一起
使用为主,不去重复发明

使用spring开发程序

spring所需要的jar包:
在这里插入图片描述
在这里插入图片描述

spring框架将对象先注册到容器里面,然后在我们使用时就可以不需要new就可以获取值

开发spring项目的步骤

  1. 加入相应jar包
    在这里插入图片描述
  2. 编写实体类
package spring.bean;

public class Girl {
    
    
	private String name;
	private int age;
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	public int getAge() {
    
    
		return age;
	}
	public void setAge(int age) {
    
    
		this.age = age;
	}
	public Girl(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
	public Girl() {
    
    
		super();
	}
	

}

  1. 在spring的配置文件里做bean对象的注册
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 将对象注册到spring的容器原理 -->
    <bean id="girl1" class="spring.bean.Girl">
    	<property name="name"><value>岳好</value></property>
    	<property name="age"><value>24</value></property>
    </bean>
</beans>
  1. 在测试类里来获取刚刚注册的对象
package Test;

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

import spring.bean.Girl;

public class TestGirl {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//先获取spring配置文件
		ApplicationContext ctx=new ClassPathXmlApplicationContext(new String("applicationContext.xml"));
		Girl girl=(Girl) ctx.getBean("girl1");
		System.out.println(girl.getName()+girl.getAge());
		//通过这个方法我们没有通过对象来new,但却获取了一个对象
	}

}

运行效果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/pengxiang1998/article/details/105509004
今日推荐