spring基础知识笔记

概述

特点:轻量级,一站式,开发框架。
核心技术:Inversion of Control (IoC,控制反转)、AOP等。

IOC容器

1、Spring 容器是 Spring 框架的核心。容器将创建对象,把它们连接在一起,配置它们,并管理他们的整个生命周期从创建到销毁。
2、Spring 容器使用依赖注入(DI)来管理组成一个应用程序的组件。这些对象被称为 Spring Beans

Bean

被称作 bean 的对象是构成应用程序的支柱也是由 Spring IoC 容器管理的。bean 是一个被实例化,组装,并通过 Spring IoC 容器所管理的对象。这些 bean 是由用容器提供的配置元数据创建的

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.xsd">

<内容>


id是Bean的唯一标识符,class表示这个Bean所依赖的类名
Bean使用
1、初始化对象
ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);
2、获取对象
HelloWorld obj = context.getBean(“h”,HelloWorld.class);
3、使用对象
obj.use();

Bean作用域

	singleton(单例)
		特点
			1、单例类只能有一个实例
			2、单例类必须自己创建自己的唯一实例
			3、单例类必须给所有其他对象提供这一实例
		一般不写scope就是默认单例
		每次引用只会有一个实例
		id的值是唯一标识
		<bean id="h" class="com.imooc.controller.HelloWorld"></bean>
		<bean id="h" class="com.imooc.controller.HelloWorld" scope="singleton"></bean>
	prototype(多例)
		<bean id="h" class="com.imooc.controller.HelloWorld" scope="prototype"></bean>
		每次引用创建一个实例
	Web应用
		request
		session
		globalsession
		application

Bean生命周期回调

	创建
		申请资源
		接口
			public interface InitializingBean{
  void afterPropertiesSet( ) throws Exception;

}
具体方法

然后创建一个类,里面有init方法
销毁
释放资源
接口
public interface DisposableBean{
void destroy( ) throws Exception;
}
具体方法

然后创建一个类,里面有destroy方法
((ConfigurableApplicationContext)context).close();
自动调用context依赖的类里的init和cleanup方法

Spring BeanFactory 容器

1、BeanFactory 容器主要的功能是为依赖注入 (DI) 提供支持,这个容器接口在 org.springframework.beans.factory.BeanFactor 中被定义。BeanFactory 和相关的接口,比如BeanFactoryAware、DisposableBean、InitializingBean,仍旧保留在 Spring 中,主要目的是向后兼容已经存在的和那些 Spring 整合在一起的第三方框架。

下面看例子:

package com.spring
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("The Message is: " + message);
}
}

package com.spring.
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainApp {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory
(new ClassPathResource(“Beans.xml”));
HelloWorld obj = (HelloWorld) factory.getBean(“helloWorld”);
obj.getMessage();
}
}

扫描二维码关注公众号,回复: 9076931 查看本文章

以下是bean.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-3.0.xsd">
         <bean id="helloWorld" class="com.spring.HelloWorld">
             <property name="message" value="Hello World!"/>
         </bean>
       </beans>

输出结果:

The Message is:Hello World!

id是Bean的唯一标识符,class表示这个Bean所依赖的类名,通过这个来改变class类里的内容,给message赋值。

Spring ApplicationContext 容器

Application Context 是 BeanFactory 的子接口。
Application Context 是 spring 中较高级的容器。和 BeanFactory 类似,它可以加载配置文件中定义的 bean,将所有的 bean 集中在一起,当有请求的时候分配 bean。 另外,它增加了企业所需要的功能,比如,从属性文件中解析文本信息和将事件传递给所指定的监听器。这个容器在 org.springframework.context.ApplicationContext interface 接口中定义。

FileSystemXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径。

ClassPathXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,因为,容器会从 CLASSPATH 中搜索 bean 配置文件。

WebXmlApplicationContext:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。

package com.spring
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}

package com.spring
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext
(“C:/Users/mcc/IdeaProjects/springweb/src/main/resources/Beans.xml”);
HelloWorld obj = (HelloWorld) context.getBean(“helloWorld”);
obj.getMessage();
}
}

获取ApplicationContext的方法
相对路径
如:ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);
绝对路径
如:ApplicationContext context = new FileSystemXmlApplicationContext(“C:/Users/mcc/IdeaProjects/springweb/src/main/resources/Beans.xml”);

以下是bean.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-3.0.xsd">
          <bean id="helloWorld" class="com.spring.HelloWorld">
              <property name="message" value="Hello World!"/>
          </bean>
       </beans>

输出结果:

The Message is:Hello World!

Spring DI(Dependency Injection,依赖注入)

接口
	定义接口
	实现接口
	以接口为基础注入

依赖注入方式

基于构造函数(强依赖)

public class Hello{
private Header header;
public Hello(Header header){
this.header = header;
}
}

通过 < constructor-arg value="" >< /constructor-arg> 设置构造函数的形式参数
当一个构造函数有多个形参时,通过
< constructor-arg name=“message” value=" value1" index=“1”>
< constructor-arg name=“message” value=" value2" index=“0”>

设置形式参数
1、如果不加index就会按照上下顺序默认,如果加了index就会根据index的值顺序来觉得注入的形参顺序
2、可以不加index,通过设置name属性来指明形参的值
当一个构造函数的形参为一个集合时

				< constructor-arg  >
        < map>
            < entry key="message" value="name">< /entry>
            < entry key="num" value="7">< /entry>
        < /map>
    < /constructor-arg>
			set
				< constructor-arg  >
        < set>
            < value>num< /value>
            < value>14< /value> 
       < /set>
    < /constructor-arg>
			list
				< constructor-arg  >
        < list>
            < value>num< /value>
            < value>14< /value> 
       < /list>
    </constructor-arg>
		当一个构造函数的形参为一个prop时
			        <constructor-arg>
        <props>
            <prop key="num">1</prop>
            <prop key="message">place</prop>
        </props>
    </constructor-arg>

基于Setter方法(可选依赖)

public class Hello{
private Header header;
public setHeader(Header header){
this.header = header;
}
}

依赖注入

基本类型(int,String)
集合
Bean
配置文件

Spring AOP(Aspect-Oriented Programming,面向切面编程)

特点

1、缺点
代码重复
耦合业务逻辑与非业务逻辑
ps:1、耦合是指两个或两个以上的体系或两种运动形式间通过相互作用而彼此影响以至联合起来的现象。

2、在软件工程中,对象之间的耦合度就是对象之间的依赖性。对象之间的耦合越高,维护成本越高,因此对象的设计应使类和构件之间的耦合最小。

3、分类:有软硬件之间的耦合,还有软件各模块之间的耦合。耦合性是程序结构中各个模块之间相互关联的度量。它取决于各个模块之间的接口的复杂程度、调用模块的方式以及哪些信息通过接口。
2、优点
代码重用
解耦业务逻辑与非业务逻辑

AOP术语

	Aspect:日志,安全等功能
	Join point:函数执行或者属性访问
	Advice:在某个函数执行点上要执行的切面功能
		Before:函数执行之前
		After returning:函数正常返回之后
		After throwing:函数抛出异常之后
		After finally:函数返回之后
		Around:函数执行前后
	Pointcut:匹配横切目标函数的表达式
非完整AOP实现
整合AOP与IoC
AOP实现的两种方式
	XML schema-based AOP
	@AspectJ annotation-based AOP

Spring Beans 装配

自动装配

	byName:根据Bean名称
	byType:根据Bean类型
	 constructor:构造函数,根据类型

基于Annotation装配Bean

@Component

		可以使用此注解描述 Spring 中的 Bean,但它是一个泛化的概念,仅仅表示一个组件(Bean),并且可以作用在任何层次。使用时只需将该注解标注在相应类上即可。

@Required

		@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常

@Repository

		用于将数据访问层(DAO层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

@Service

		通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

@Controller

		通常作用在控制层,用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

@Autowired

		1、@Autowired 注释对在哪里和如何完成自动连接提供了更多的细微的控制
		2、@Autowired 注释可以在 setter 方法中被用于自动连接 bean,就像 @Autowired 注释,容器,一个属性或者任意命名的可能带有多个参数的方法

@Resource

		其作用与 Autowired 一样。其区别在于 @Autowired 默认按照 Bean 类型装配,而 @Resource 默认按照 Bean 实例名称进行装配。
		@Resource 中有两个重要属性:name 和 type。Spring 将 name 属性解析为 Bean 实例名称,type 属性解析为 Bean 实例类型。如果指定 name 属性,则按实例名称进行装配;如果指定 type 属性,则按 Bean 类型进行装配。

@Qualifier

		可能会有这样一种情况,当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配,在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱
		与 @Autowired 注解配合使用,会将默认的按 Bean 类型装配修改为按 Bean 的实例名称装配,Bean 的实例名称由 @Qualifier 注解的参数指定。

@PostConstruct&@PreDestory

		生命周期回调
	JSR-250注释
		@PostConstruct
			 作为初始化回调函数的一个替代
				
		@PreDestroy 
			作为销毁回调函数的一个替代
				
		需要注册一个关闭钩 registerShutdownHook() 方法,该方法在 AbstractApplicationContext 类中被声明。这将确保一个完美的关闭并调用相关的销毁方法。

基于Java的配置

@Configuration

			带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源

@Bean

			@Bean 注解告诉 Spring,一个带有 @Bean 的注解方法将返回一个对象,该对象应该被注册为在 Spring 应用程序上下文中的 bean
			 @Bean 注解的方法名称作为 bean 的 ID,它创建并返回实际的 bean。你的配置类可以声明多个 @Bean。一旦定义了配置类,你就可以使用 AnnotationConfigApplicationContext 来加载并把他们提供给 Spring 容器

@import

			注解允许从另一个配置类中加载 @Bean 定义
			如

@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}

@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B a() {
return new A();
}
}

当实例化上下文时,不需要同时指定 ConfigA.class 和 ConfigB.class,只有 ConfigB 类需要提供

public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(ConfigB.class);
// now both beans A and B will be available…
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}
子主题 3

以上两个等价

Spring 数据访问

数据库访问,JDBC

DAO(Data Access Object)

		数据访问相关接口
	ORM(Object Relation Mapping)
		对象关系映射
传统JDBC
		1、加载数据库驱动
		2、获得数据库连接
		3、创建statement
		4、执行SQL语句
		5、遍历结果
		6、异常处理
		7 、清理资源
		
	数据访问的步骤
		1、连接参数
		2、打开连接
		3、声明SQL语句以及参数
		4、执行SQL,并循环访问结果
		5、执行业务
		6、处理异常
		7、关闭连接,语句以及结果集
spring里的数据访问
		DataSource接口
			主要内容
				驱动类名
				连接地址
				用户名
				密码
			两个接口
				DriverManagerDatasource
				BasicDataSource
		JdbcTemplate
			
		namedParameterJdbcTemplate
			包含了jdbcTemplate
			
			queryForObject(String sql,Map<String,?> paramMap, RowMapper<T> rowMapper)
			queryForObject(String sql,SqlParameterSource paramSource, Class<T> requiredType)
			SqlParameterSource
				MapSqlParameterSource
				BeanPropertySqlParameterSource
				
			都在org.springframework.jdbc.core.namedparam
		jdbcTemplate的缺点:

1、jdbcTemplate.queryForObject方法入参不支持以Map的形式传递参数,需要按照sql语句中参数的顺序组织入参的List。
2、jdbcTemplate.queryForObject方法直接不支持的in查询。只支持Integer.class String.class 这种单数据类型的入参。

事务管理

	JDBC事务管理			
![jdbc事务管理]
(https://img-blog.csdnimg.cn/20191008120022802.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01DQ3p6enp6enp6enp6eg==,size_16,color_FFFFFF,t_70)
	Hibernate事务

Spring事务管理

		统一的事务编程模型
		编程式事务及声明式事务(AOP)
		org.springframework.transaction
		
		TransactionDefination
			getName:事务名称
			getIsolationLevel:隔离级别
			getPropagationBehavior:传播行为
			getTimeout:超时时间
			isReadOnly:是否只读事务
		TransactionStatus
			isNewTransaction:是否是新的事务
			hasSavepoint:是否有savepoint(诊断,NESTED)
			isCompleted:是否已完成
			isRollbackOnly:事务结果是否是rollback-only
			setRollbackOnly:设置事务为rollback-only(TransactionTemplate)
		隔离级别
			ISOLATION_READ_UNCOMMITTED:读未提交
			ISOLATION_READ_COMMITTED:读提交
			ISOLATION_REPEATABLE:串行化
			ISOLATION_DEFAULT:默认
		传播行为

Spring MVC 模式

核心:数据与视图分离
DispatcherServlet
	DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自己定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。

DispatcherServlet是前端控制器设计模式的实现,提供Spring Web MVC的集中访问点,而且负责职责的分派,而且与Spring IoC容器无缝集成,从而可以获得Spring的所有好处。
配置web.xml:

 <servlet>
 <servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
 <url-pattern>*.form</url-pattern>
</servlet-mapping>

DispatcherServlet中的Bean

Controller

			处理器/页面控制器,但控制逻辑转移到前端控制器了,用于对请求进行处理
			定义
				如:<context:component-scan base-package="com.netease.course"/>
			@RequestMapping
				一些重要参数
					name:名称
					value & path:路径,如“/hello”
					method:请求方法,如“GET”
					params:请求参数
					headers:请求头
					consumes:请求的媒体类型,“Content-Type”
					produces:响应的媒体类型,“Accept”
				使用
					@RequestMapping(path = "/user/{userId:[a-z]+}")

public String webMethod(@PathVariable String userId){
//do work
}
@RequestMapping(value = “/user”)
public void user(HttpServletResponse response) throws IOException{
response.getWriter().write(“Hello,Spring Web”);
}
函数参数
HttpServletRequest / HttpServletResponse,HttpSession(Servlet API)
Reader/Writer
@PathVariable
@RequestParam
HttpEntity
@RequestBody
Map/Model/ModelMap/view/ModelAndView
函数返回值
void
String:view名称,@ResponseBody
HttpEntity
View
Map
Model
ModelAndView
函数实现
向网页传数据

表单
上传文件
配置bean:


HttpEntity
@RequestBody&ResponseBody
返回对象
MessageConverter
RequestBody - Object:参数
ResponseBody - Object:返回值
使用这个只需要在beans里添加<mvc:annotation-driven />
再添加一些依赖
就能实现访问一个Java对象时,返回json对象

HandlerMapping

			请求到处理器的映射,如果映射成功返回一个HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象、多个HandlerInterceptor拦截器)对象;

如BeanNameUrlHandlerMapping将URL与Bean名字映射,映射成功的Bean就是此处的处理器;

HandlerAdapter

			HandlerAdapter将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,从而很容易支持很多类型的处理器;

如SimpleControllerHandlerAdapter将对实现了Controller接口的Bean进行适配,
并且按处理器的handleRequest方法进行功能处理;

ViewResolver(View解析)

			ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术;

如InternalResourceViewResolver将逻辑视图名映射为jsp视图;

ContextLoaderListener
      	<listener> 
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring-base.xml</param-value>
 </context-param>
发布了4 篇原创文章 · 获赞 2 · 访问量 177

猜你喜欢

转载自blog.csdn.net/MCCzzzzzzzzzzzz/article/details/102379000