Spring01环境搭建

Spring的3大主要功能:
1. ioc/di
2. aop
3. 声明式事务

一、IOC

ioc:由spring容器去创建实例,不再需要程序员去new实例。
控制:控制类的对象
反转:转交给spring容器去完成
最大作用:解耦(解除了<创建对象和程序员的耦>)

二、Spring环境搭建

  1. 创建一个web项目
  2. 导入核心功能的jar包
    在这里插入图片描述
  3. 新建applicationContext.xml
    (文件名和路径自定义)
    applicationContext.xml中配置的信息最终都存储在ApplicationContext容器中。
    在这里插入图片描述
    spring 配置文件基于schema(语法检查器),每次引入xsd时,就是一个xmlns
    schema最大的优点就是:扩展性
<?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">
</beans>

——————————————————————————-spring环境搭建完毕————————————————————————

三、例子: 创建对象

  1. 创建对象
    在这里插入图片描述在这里插入图片描述从类路径classes下加载一个xml文件,最后配生成ApplicationContext
    在这里插入图片描述
package com.company.pojo;

public class People {
	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; }
	
	@Override
	public String toString() {
		return "People [name=" + name + ", age=" + age + "]";
	}	
}

<?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">
    <!-- id表示获取到对象标识
    	 class 创建哪个类的对象
     -->
    <bean id="peo" class="com.bjsxt.pojo.People"/>
</beans>
/*编写测试类*/
package com.company.test;

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

import com.company.pojo.People;

public class Test {
	public static void main (String[] args) {
		//没有Spring的写法
//		People people = new People();
		
		//使用Spring的IOC功能,需要将People转交给Spring,就得在xml文件中配置<bean id="获取类的标识" calss="全路径名"/>
		//配置文件被加载时,实例就被创建
		//加载配置文件,形成容器ApplicationContext
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		People people = ac.getBean("peo",People.class);
		System.out.println(people);
		
//		String[] names = ac.getBeanDefinitionNames();	//获取容器中的所有pojo
//		for (String string : names) {
//			System.out.println(string);
//		}
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值