SSM系列学习笔记之Spring

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44815052/article/details/95927405

Spring介绍

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
Spring就是一个大工厂,专门负责生产Bean,可以将所有对象创建和依赖关系维护由Spring管理,Bean实际上就是一个new好放在Spring容器中的对象。

Spring快速入门

  1. 导入Spring的核心jar包
    Spring-beans-xxxx.RELEASE.jar
    spring-context-xxxx.RELEASE.jar
    Spring-expression-xxxx.RELEASE.jar
    spring-core-xxxx.RELEASE.jar
    com.springsource.org.apache.commons.logging-xxxx.jar

  2. IoC创建实例
    1).写一个配置文件Bean.xml,相关约束如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- dtd约束 -->
<!-- bean definitions here -->

</beans>
<?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">
<!-- xsd约束 -->
<!-- bean definitions here -->

</beans>

2).在配置文件中定义所需要的Bean,由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">
<!-- bean definitions here -->

<bean  id="userService"  class="com.wsz.service.Impl.UserServiceImpl"/>
</beans>
  1. 从Spring容器中获取Bean
//根据Bean.xml的类路径来创建ApplicationContext  对象
ApplicationContext  applicationContext  = new 
			ClassPathXmlApplicationContext ( "/Bean.xml" );
//根据id获取Bean
UserService userService = (UserService)  applicationContext.getBean("userService");
//使用Bean
........

概念

IoC : Inverse of Control,控制反转,就是将创建对象的控制权交给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">
<!-- bean definitions here -->
<!-- 假设UserServiceImpl有一个私有属性name,并有get/set方法-->
<bean  id="userService"  class="com.wsz.service.Impl.UserServiceImpl">
<property  name="name"  value="zhangsan" />
</bean>
</beans>

以上代码相当于

UersService us = new UserServiceImpl();
us.setName("zhangsan");

概念

DI :Dependency Injection 依赖注入,简单地说,就是Spring在创建一个Bean时,根据xml文件的配置给Bean的属性赋值。

Bean的两个常见作用域:

类别 说明
singleton 单例,即在Spring IoC容器中仅存在一个Bean实例。默认值
prototype 多例,每次从容器中调用Bean时,都返回一个新的实例
<!-- 修改作用域 -->
<bean  id="userService"  class="com.wsz.service.Impl.UserServiceImpl"  scope="prototype"/>

集合注入

假如对象中有集合属性,注入时都是给添加子标签,每个子标签中放一个数据。

<property  name="cars">
	<List>
			<value>单车</value>
	</List>

猜你喜欢

转载自blog.csdn.net/weixin_44815052/article/details/95927405