Spring基础入门案例

- spring的两大核心

  • 1.IOC控制反转 :管理对象和依赖关系维护,依赖注入(DI),依赖关系维护通俗一点讲就是给字段赋值。
  • 2.AOP:面向切面编程。

- spring 入门

1.创建动态web工程导入spring需要的包(core,context,beans,expression)以及依赖包(logging)
2.在工程下创建resource源文件夹来,然后在resource创建applicationContext.xml文件来配置spring。
3.百度spring约束或者在这里复制spring的申明和约束。

<?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>

4.创建一个类来做测试。

public class Tomato {
	public void execute(){
		System.out.println("我很美味。。。。");
	}
}

5.在spring配置文件中,配置Bean,注册Bean。

<!-- 
	Spring中管理的对象称之为bean ,
	class="创建对象所属类的完全限定名",
	id是区分容器中对象的唯一标识,方便获取,也可以是name属性
-->
<bean id="tomato" class="cn.itshow.bean.Tomato"></bean>

6.创建测试类中将Spring容器的实例化
方式一:

//第一种方式:BeanFactory (过时了)
//读取类路径 ClassPath下的资源文件applicationContext.xml
ClassPathResource resource = new ClassPathResource("applicationContext.xml");
//将资源文件交给BeanFactory去创建容器对象
BeanFactory factory = new XmlBeanFactory(resource);// 创建BeanFactory对象 ,并把配置文件交给BeanFactory对象(BeanFactory 是一个接口所以这里用的他的子类,使用了多态的方式创建对象)。

方式二:ApplicationContext【常用】

//接口ApplicationContext extends BeanFactory -- ApplicationContext功能要多一些
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

然后获取Bean对象,使用该对象。
方式一:Tomato t = factory.getBean(“tomato”,Tomato.class);
方式二:Tomato t = (Tomato)ac.getBean(“tomato”);
解释:根据配置文件中的id值去获取对象,返回是一个Object需要强转。
(以上入门案例测试主要是为了获取实例类的对象。)

发布了23 篇原创文章 · 获赞 1 · 访问量 166

猜你喜欢

转载自blog.csdn.net/weixin_45528650/article/details/105556935