脚本宝典收集整理的这篇文章主要介绍了Spring学习笔记,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
spring理念:是现有的技术更加容易使用,本身是一个大杂烩。
官网: https://spring.io/projects/spring-framework#overview
官方下载: https://repo.spring.io/release/org/springframework/spring/
GITHub: https://github.COM/spring-projects/spring-framework
Spring Web MVC » 5.2.5.RELEASE
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dePEndency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
总结:spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。
组成
拓展
现代化java开发
Spring Boot
Spring Cloud
SpringCloud是基于SpringBoot实现的。
Spring SpringMVC SpringBoot
在之前,用户的需求可能会影响原来的代码。
使用一个set。
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。 采用xml方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。 控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入(Dependency Injection,Dl)。
package com.kuang.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@override
public String toString() {
return "Hello{" +
"str='" + str + ''' +
'}';
}
}
1.使用无参构造创建对象,默认!
2.假设要使用有参构造创建对象。
1.下标赋值
<!-- 有参构造下标赋值-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg index="0" value="小王二"/>
</bean>
2.通过类型创建
<!-- 不建议使用,当有两个相同类型时无法判断-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg type="java.lang.String" value="小王三"/>
</bean>
3.参数名
<!-- 第三种直接通过参数名-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg name="name" value="小王四"/>
</bean>
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
<!--
id:bean的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的全限定名:包名+类名
name:别名 name可以同时取多个别名
-->
<bean id="userT" class="com.kuang.pojo.UserT" name="user2 u2,u3;u4">
<property name="name" value="小王五"/>
</bean>
一般用于团队开发,可以将多个配置文件导入合并为一个
使用applicationContext.xML即可
【环境搭建】
1.复杂类型
package com.kuang.pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.真实测试对象
public class Student {
private String name;
private Address address;
private String[] Books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private Properties info;
private String wife;
}
3.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.kuang.pojo.Student">
<!-- 普通值注入,value-->
<property name="name" value="小王六"/>
</bean>
</beans>
4测试类
public class Mytest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student.getName());
}
}
完善注入信息
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="长沙"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!-- 普通值注入,value-->
<property name="name" value="小王六"/>
<!-- Bean注入,ref-->
<property name="address" ref="address"/>
<!-- 数组注入,ref-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!-- list-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>画画</value>
<value>吃饭</value>
</list>
</property>
<!-- Map-->
<property name="card">
<map>
<entry key="身份证" value="1234567812345678"/>
<entry key="银行卡" value="62222265652222"/>
</map>
</property>
<!-- Set-->
<property name="games">
<set>
<value>LOL</value>
<value>yjwj</value>
<value>jw3</value>
</set>
</property>
<!--null-->
<property name="wife" value=""/>
<!--Properties-->
<property name="info">
<props>
<prop key="学号">20210728</prop>
<prop key="性别">男</prop>
<prop key="姓名">小王七</prop>
</props>
</property>
</bean>
</beans>
我们可以使用p命名空间和c命名空间进行注入
官方解释:
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p 命名空间注入 可以直接注入属性的值:property-->
<bean id="user" class="com.kuang.pojo.User" p:name="小王" p:aeg="18"/>
<!-- c 命名空间注入 通过构造器注入:constructs-args-->
<bean id="user2" class="com.kuang.pojo.User" c:aeg="18" c:name="小王二"/>
</beans>
测试:
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
注意:
p命名和c命名空间不能直接使用需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext . |
session | Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in the context of a web-aware Spring ApplicationContext . |
application | Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in the context of a web-aware Spring ApplicationContext . |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the context of a web-aware Spring ApplicationContext . |
1.单例模式(Spring默认机制)
<bean id="user" class="com.kuang.pojo.User" p:name="小王" p:aeg="18" scope="singleton"/>
2.原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="user" class="com.kuang.pojo.User" p:name="小王" p:aeg="18" scope="prototype"/>
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user2", User.class);
System.out.println(user==user2); //false
System.out.println(user.hashCode());//1605851606
System.out.println(user2.hashCode());//1267556427
}
3.request、session、application、只能在web开发中使用
三种自动装配
1.在xml中显示配置
2.在java中显示配置
3.隐式的自动装配bean【重要】
环境搭建 一个人有两个宠物!
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byName">
<property name="name" value="小王三"/>
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.kuang.pojo.Cat"/>
<bean class="com.kuang.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
<property name="name" value="小王三"/>
</bean>
</beans>
小结:
byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。
byType的时候需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
使用注解须知
1.导入约束.context约束
2.配置注解的支持: context:annotation-config/
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
@Autowired
直接在属性上使用即可!也可以在set方式上使用
使用Autowired我们可以不用编写Set方法,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname
@Nullable 字段标记了这个注解,说明这个字段可以为null。
public @interface Autowired {
boolean required() default true;
}
public class People {
//如果显示定义了 Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
如果@Autowired自动装配环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时我们可以使用@Qualifier(value = "xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入!
小结
@Resource和Autowire的区别:
都是用来装配的都可以放在属性字段上
@Autowire通过byType的方式实现必须要求 这个对象存在
@Resource默认通过byName方式实现如果找不到名字则通过byType实现 如果两个都找不到就报错。
执行顺序不同:@Autowire通过byType的方式实现。@Resource默认通过byName方式实现。
使用注解开发要保证aop包导入
使用注解要导入context约束增加注解支持
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
bean
属性如何注入
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.component;
//等价于 <bean id=“user” class="com.kuang.pojo.User"/>
//Component 组件
@Component
public class User {
public String name = "小王";
//等价于 <property name="name" value="王小二"/>
@Value("王小二")
public void setName(String name) {
this.name = name;
}
}
衍生的注解
自动装配置
@Autowired :自动装配通过类型。名字 如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
@Nullable字段标记了这个注解,说明这个字段可以为null; @Resource :自动装配通过名字。类型。
作用域
@Scope("prototype")
小结
xml与注解
xml与注解的最佳实践:
<!-- 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="com.kuang"/>
<context:annotation-config/>
JavaConfig是Spring的一个子项目,Spring4之后成为核心功能
实体类
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这个注解的意思就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("小王")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + ''' +
'}';
}
}
配置文件
package com.kuang.config;
import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
//这个也会被Spring容器托管注册到容器中因为他本来就是一个@Component。
// @Configuration代表这是一个配置类,等价于beans.XML
@ComponentScan("com.kuang.pojo")
@Import(WangConfig2.class)
public class WangConfig {
//注册一个Bean相当于之前写的一个Bean标签
//bean标签中的id属性,为方法名。
//这个方法的返回值为bean标签的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入bean的对象
}
}
测试类
public class MyTest {
public static void main(String[] args) {
//如果完全使用配置类方式,我们就只能通过AnnotationConfig上下文来获取容器通过配置类的class对象加载
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WangConfig.class);
User getUser = context.getBean("getUser", User.class);
System.out.println(getUser.getName());
}
}
SpringAOP的底层【SpringAOP和SpringMVC】
代理模式的分类:
角色分析:
代码步骤:
接口
//租房
public interface Rent {
public void rent();
}
真实角色
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东需出租房子");
}
}
代理角色
public class Proxy implements Rent {
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
seeHouse();
host.rent();
hetong();
fare();
}
public void seeHouse(){
System.out.println("中介带你看房");
}
public void hetong(){
System.out.println("签租赁合同");
}
public void fare(){
System.out.println("收中介费");
}
}
客户端访问代理角色
public class Client {
public static void main(String[] args) {
//房东需要出租房子
Host host = new Host();
//代理,中介帮房东出租房子。代理角色会有一些附属操作。
Proxy proxy = new Proxy(host);
//你不用面对房东直接找中介租房即可
proxy.rent();
}
}
静态代理模式的好处:
缺点:
需要了解两个类:Proxy:代理、InvocationHandler:调用处理程序
动态代理模式的好处:
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
方式一:使用Spring的API接口实现AOP【主要是Spring的API接口实现】
方式二:自定义类来实现AOP【主要是切面定义】
方式三:使用注解实现
步骤:
导入相关jar包
编写配置文件
测试
编写数据源配置
SQLSessionFactory
sqlSessionTemplate
给接口加实现类
将实现类注入Spring中
测试
事务的ACID原则
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置
这里使用Spring提供的jdbc-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverclassname" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 绑定Mybatis配置文件 -->
<property name="configLocation" value="mabatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/kuang/mapper/UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate:就是SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="datasource" />
</bean>
<!--结合aoP实现事务置入-->
<!--配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txpointCut" exPression="execution(* com.kuang.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpointCut"/>
</aop:config>
</beans>
为什么需要事务?
以上是脚本宝典为你收集整理的Spring学习笔记全部内容,希望文章能够帮你解决Spring学习笔记所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。