1.spring
1.1 简介
-
2002,首次推出了spring框架的雏形:interface21框架
-
spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
-
spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
-
SSH:Struct2+spring+Hibernate
-
SSM:SpringMVC+spring+mybatis
官方下载地址: repo.spring.io/release/org…
GitHub:github.com/spring-proj…
1.2 优点
- spring是一个免费的开源的框架(容器)
- spring是一个轻量级的、非入侵式(不改变原有代码)的框架
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持
==总结一句话:spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架==
1.3 组成
1.4 拓展
2. IOC理论推导
在之前的业务中,用户的需求可能会影响我们的代码,我们需要根据用户的需求去修改源代码
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImpl(); // 对象固定
public void getUser() {
userDao.getUser();
}
}
public class IocTest {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();// 每次用户调用不同接口都需要修改这个对象
userService.getUser();
}
}
通过set动态实现值的注入
public class UserServiceImpl implements UserService{
private UserDao userDao;
//通过set方法注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void getUser() {
userDao.getUser();
}
}
public class IocTest {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
((UserServiceImpl) userService).setUserDao(new UserDaoImpl());//这样用户可以修改这个对象
userService.getUser();
}
}
IOC本质
ioc(Inversion of Control):控制反转 是一种设计思想 而DI(Dependency Injection) 依赖注入 是一种实现方式
没有IOC的程序中,我们使用面向对象编程,对象的创建于对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己来控制,控制反转,把对象的创建交由第三方
原来程序的对象由程序员创建,通过第三方注入,程序的对象由主动创建到被动接收
解决了上述的问题
3. IOC创建对象的方式
- 使用无参构造创建对象 【默认】
- 使用有参构造创建对象
- 下标赋值
<bean id="student" class="pojo.Student">
<constructor-arg index="0" value="11"/>
</bean>
- 类型 //不建议使用
<bean id="student" class="pojo.Student">
<constructor-arg type="java.lang.Integer" value="11"/>
</bean>
- 参数名
<bean id="student" class="pojo.Student">
<constructor-arg name="age" value="11"/>
</bean>
4. Spring配置
4.1 别名
<!-- 如果取了别名,可以通过这个别名获取这个对象-->
<alias name="student" alias="123321"/>
4.2 bean的配置
<!--
id :bean 的唯一标识符,相当于之前学的对象名
class :bean对象所对应的全限定名:包名+类型
name: 也是别名
-->
<bean id="student" class="pojo.Student" name="sada">
<constructor-arg name="age" value="11"/>
</bean>
5. 依赖注入
5.1 构造器注入
<bean id="student" class="pojo.Student">
<constructor-arg name="age" value="11"/>
</bean>
5.2 set注入
依赖注入:Set注入!
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
<bean id="address" class="com.axj.pojo.Address">
<property name="address" value="广州"/>
</bean>
<bean name="student" class="com.axj.pojo.Student">
<!--第一种,普通值注入,value-->
<property name="name" value="子船"/>
<!--第二种,Bean注入,ref-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>java核心技术卷1</value>
<value>图解http</value>
<value>图解tcp/ip</value>
</array>
</property>
<!--List-->
<property name="hobbys">
<list>
<value>篮球</value>
<value>足球</value>
<value>唱歌</value>
</list>
</property>
<!--Map-->
<property name="grade">
<map>
<entry key="语文" value="92"/>
<entry key="数学" value="100"/>
<entry key="英语" value="80"/>
</map>
</property>
<!--Set-->
<property name="games">
<set>
<value>dota2</value>
<value>王者荣耀</value>
<value>吃鸡</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--properties-->
<property name="info">
<props>
<prop key="driver"></prop>
<prop key="rul"></prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
5.3 拓展注入
注意点:配置约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
5.4 bean的作用域
1.单例模式(Spring默认机制)
<bean id="user" class="com.axj.pojo.User" scope="singleton"/>
2.原型模式:每次从容器中get的时候,都会产生一个新对象!
<bean id="user" class="com.axj.pojo.User" scope="prototype"/>
6. bean的自动装配(autowire)
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并给bean装配属性
在spring中有三种装配方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean 【重要】
6.1 byName自动装配
<bean id="dog" class="axj.pojo.Dog"/>
<bean id="cat" class="axj.pojo.Cat"/>
<!--byName:会自动在上下文容器中寻找 和自己对象set方法后面的值对应的beanid-->
<bean id="people" class="axj.pojo.People" autowire="byName"/>
6.2 byType自动装配
<bean id="dog" class="axj.pojo.Dog"/>
<bean id="cat" class="axj.pojo.Cat"/>
<!--byName:会自动在上下文容器中寻找 和自己对象set方法后面的值对应的beanid-->
<!--byType:会自动在容器上下文中寻找 和自己对象属性类型相同的bean-->
<bean id="people" class="axj.pojo.People" autowire="byType"/>
小结:
- 使用byName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- 使用byType的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
6.3 使用注解实现自动装配
jdk1.5支持的注解,spring2.5就支持注解了
使用注解须知:
- 导入约束
- 配置注解的支持 : 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>
@Autowried
自己在属性上使用即可! 也可以在set方式上使用
使用Autowired 我们可以不用编写Set方法了,前提是这个自动装配的属性在IOC容器中存在,且符合名字byname
public class People {
private String name;
//如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Dog dog;
@Autowired
private Cat cat;
@Qualifier 指定特定的beanid
@Autowired(required = false)
@Qualifier(value = "dog123")
private Dog dog;
@Autowired
@Qualifier(value = "cat123")
private Cat cat;
7. 使用注解开发
//等价于<bean id="user" class="com.axj.pojo.User"/>
//@Component 组件
@Component
@Scope("singleton")
public class User {
public String name;
//相当于<property name="name" value="子船1"/>
@Value("子船1")
public void setName(String name) {
this.name = name;
}
}
6.小结
-
xml与注解
-
xml更加万能,适合如何场合!维护简单方便
-
注解 不是自己类使用不了,维护相对复杂xml与注解最佳实践:
-
xml用来管理bean;
-
注解只负责完成属性的注入;
-
我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.axj.pojo"/>
<context:annotation-config/>
8. 使用java的方式配置spring
可以完全不使用spring的xml配置,全权交给java来做
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("aaaaaaa")
public void setName(String name) {
this.name = name;
}
}
import com.axj.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会被spring容器托管,注册到容器中,因为他本来就是一个@Component
// @Configuration代表这是一个配置类,就和我们之前看的beans.xml
@Configuration
@ComponentScan("com.axj.pojo")
public class AxjConfig {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();
}
}
public class Test {
public static void main(String[] args) {
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(AxjConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}
9. AOP(动态代理)
9.1 什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生泛型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
9.2 AOP在Spring中的作用
==提供声明式事务;允许用户自定义切面==
- 横切关注点:跨越应用程序多个模块的方法或功能。既是,与我们业务逻辑无关的,但是我们需要关注的部分,既是横切关注点。如日志,安全,缓存,事务等等...
- 切面(ASPECT):横切关注点 被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的“地点”的定义
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持五种类型的Advice:
即AOP在不改变原有代码的情况下,去增加新的功能
9.3 使用Spring实现AOP
使用AOP织入,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
- 方式一: 使用Spring的API接口【主要SpringAPI接口实现】
applicationContext.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"
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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.axj.service.UserServiceImpl"/>
<bean id="log" class="com.axj.log.Log"/>
<bean id="afterLog" class="com.axj.log.AfterLog"/>
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式, execution(要执行的位置!* * * * *)-->
<aop:pointcut id="pointCut" expression="execution(* com.axj.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加 -->
<aop:advisor advice-ref="log" pointcut-ref="pointCut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointCut"/>
</aop:config>
</beans>
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//args: 参数
//target: 目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue: 返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
- 方式二: 自定义类来实现AOP【主要是切面定义】
package com.axj.diy;
public class Diy {
public void before(){
System.out.println("========执行方法前========");
}
public void after(){
System.out.println("========执行方法后========");
}
}
<?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: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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.axj.service.UserServiceImpl"/>
<!--方式二:自定义类-->
<bean id="diy" class="com.axj.diy.Diy"/>
<aop:config>
<!--自定义切面 ref:要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="pointCut" expression="execution(* com.axj.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointCut"/>
<aop:after method="after" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
</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"
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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.axj.service.UserServiceImpl"/>
<!--方式三:注解实现-->
<bean id="zs" class="com.axj.diy.Zs"/>
<!--开启注解支持!-->
<aop:aspectj-autoproxy/>
</beans>
@Aspect //标注这个类是一个切面
public class Zs {
@Before("execution(* com.axj.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("========执行方法前========");
}
@After("execution(* com.axj.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("========执行方法后========");
}
}
10 整合mybatis
spring-dao.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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--dataSource:使用spring的数据源替换mybatis的配置 c3p0 dbcp druid-->
<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=false&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配置文件 可以在这里替换mybatis配置文件中的值
properties、settings、typeAliases等等
-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/axj/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate就是之前使用的sqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能用构造器注入, 没有set方法 -->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="com.axj.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<bean id="userService" class="com.axj.service.UserServiceImpl">
<property name="userMapper" ref="userMapper"/>
</bean>
</beans>
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
public class Test {
public static void main(String[] args) throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserService userService = context.getBean("userService", UserService.class);
List<User> users = userService.selectUser();
for (User u:
users) {
System.out.println(u);
}
}
}