文章目录
ioc创建对象的四种方式
<!--ioc创建对象的方式 第一种 使用无参构造方法-->
<bean id="user" class="com.szk.pojo.User">
<!-- value放单个的,ref用于存放被spring接管的bean(id)-->
<property name="name" value="kunge"/>
<!-- </bean>-->
<!-- 第二种 ,使用有参构造方法的时候,通过下标赋值-->
<bean id="user" class="com.szk.pojo.User">
<constructor-arg index="0" value="坤哥"/>
</bean>
<!-- 第三种,通过类型创建(当有两个一样类型的参数时就不行了,不推荐使用)-->
<bean id="user" class="com.szk.pojo.User">
<constructor-arg type="java.lang.String" value="kun"/>
</bean>
<!-- 第四种,通过参数名 -->
<bean id="user" class="com.szk.pojo.User">
<constructor-arg name="name" value="shi"/>
</bean>
set注入的8中方式
<bean id="student" class="com.szk.pojo.Students">
<!--set注入第一种,普通值注入,使用value -->
<property name="name" value="szk"/>
<!--第二种,ref注入-->
<property name="address" ref="address"/>
<!--第三种,数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>三国</value>
<value>水浒传</value>
<value>西游</value>
</array>
</property>
<!--第四种,list注入-->
<property name="hobby">
<list>
<value>听哥</value>
<value>看电影</value>
<value>打游戏</value>
<value>吃火锅</value>
</list>
</property>
<!--第五种,map注入-->
<property name="map" >
<map>
<entry key="电话" value="111111"/>
<entry key="身份证" value="22222"/>
</map>
</property>
<!--第六种,set注入-->
<property name="games" >
<set>
<value>王者荣耀</value>
</set>
</property>
<!--第七种,null注入(value=""或者)-->
<property name="wife" >
<null/>
</property>
<!--第八种,-->
<property name="info" >
<props>
<prop key="学号">3333</prop>
<prop key="年龄">18</prop>
</props>
</property>
</bean>
作用域
<!-- scope="singleton" 单例模式,全局只有一个 且默认是单例模式 -->
<bean id="user" class="com.szk.pojo.User" p:name="张三" p:age="18" scope="singleton"/>
<!--scope="prototype"原型模式,每次从容器中get的时候,都会产生一个新的对象-->
<bean id="user2" class="com.szk.pojo.User" c:name="李四" c:age="18" scope="prototype"/>
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"
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:component-scan base-package="xx"/>
<!-- 启用注解-->
<context:annotation-config/>
</beans>
注解说明
- @Autowired :自动装配通过类型。名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xx”) - @Nullable 字段标记了这个注解,说明这个字段可以为null;
- @Resource :自动装配通过名字。类型。
- @Component:组件,放在类上,说明这个类被Spring管理了,就是bean! 相当于
<bean id="user" class="com.szk.pojo.User"/>
- @Value(“sss”) 相当于
<property name="name" value="sss"/>
- @Scope(“prototype”)放在类上 可以配置单例模式还是原型模式
- @ResponseBody加了这个注解,他就不会走视图解析器,会直接返回一个字符串
@Resource和@Autowired的区别:
-
都是用来自动装配的,都可以放在属性字段上
-
@ Autowired通过byType的方式实现,而且必须要求这个对象存在! [常用]
-
@ Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现! 如果两个都找不到的情况
下,就报错! [常用] -
执行顺序不同: @ Autowired通过byType的方式实现。@ Resource默认通过byname的方式实现。
-
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解[@Autowired] 完成的时候、我们可以使用@Qualifier(value="xx’ )去配置@Autowired的使用,指定一个唯一的bean对象注入!
-
@Resource(java的注解,也有name=“xx”的属性,相当于byname和bytype的集合)
byname、bytype自动装配
-
autowire="byName"自动装配,和对象set方法后面的值对应的bean的id(不可以把bean中的id省略,根据id查找)
autowire="byType"自动装配,和自己对象属性相同的bean(可以把bean中的id省略,根据class查找) -
byname的时候,需要保证所有bean的id唯一, 并月这个bean需要和自动注入的set方法的值一致!
-
bytype的时候,需要保证所有bean的class唯一, 并月这个bean需要和自动注入的属性的类型一致!
Component衍生的注解
-
@Component有几个衍生注解,我们在web开发中, 会按照mvc三层架构分层!
-
dao [@Repository]
-
service [ @Service ]
-
controller [@Controller]
这四个注解功能都是一样的, 都是代表将某个类注册到Spring中,装配Bean代理模式
角色分析:
-
抽象角色: - -般会使用接口或者抽象类来解决
-
真实角色:被代理的角色
-
代理角色:代理真实角色,代理真实角色后,我们一-般会做一 些附属操作
-
客户:访问代理对象的人
代理模式的好处:
-
可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
-
公共也就就交给代理角色!实现了业务的分工!
-
公共业务发生扩展的时候,方便集中管理!
缺点:
- 一个真实角色就会产生-个代理角色;代码量会翻倍开发效率会变低~
动态代理
1.接口
//接口
public interface Rent {
public void rent();
}
2.真实角色
//房东,真实角色
public class House implements Rent{
@Override
public void rent() {
System.out.println("房东准备把房子租出去");
}
}
3.方法类(生成动态代理的方法)
//该类自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object jiekou;
public void setJiekou(Object jiekou) {
this.jiekou = jiekou;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),jiekou.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,是使用反射实现
Object invoke = method.invoke(jiekou, args);
return invoke;
}
}
4.租房子的人
public class Client {
public static void main(String[] args) {
//真实角色
House house =new House();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setJiekou(house);
//这里的proxy就是动态生成的代理类
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
aop
Aop在Spring中的作用:提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部
分,就是横切关注点。如日志,安全,缓存,事务等等… - 切面(ASPECT) :横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice) :切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target) :被通知对象。
- 代理(Proxy) :向目标对象应用通知之后创建的对象。
- 切入点(PointCut) :切面通知执行的“地点”的定义。
- 连接点(JointPoint) :与切入点匹配的执行点。
1. 方式一:使用原生Spring API接口【主要是Spring API接口实现】
导入一个依赖
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
原本的事务逻辑,增删改查
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
实现类
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("添加");
}
@Override
public void delete() {
System.out.println("删除");
}
@Override
public void update() {
System.out.println("修改");
}
@Override
public void select() {
System.out.println("查询");
}
}
在方法执行前后增加日志的方法
public class BeforeLog implements MethodBeforeAdvice {
//method:要执行的对象的方法
//args:参数
//object:目标对象
@Override
public void before(Method method, Object[] args, Object object) throws Throwable {
System.out.println(object.getClass().getName()+"的"+method.getName()+"方法被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值,其他三个和beforelog中的值一样
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object object) throws Throwable {
System.out.println(method.getName()+"方法被执行,返回值为"+returnValue);
}
}
xml配置
<!-- 注册bean-->
<bean id="user" class="com.szk.service.UserServiceImpl"/>
<bean id="before" class="com.szk.log.BeforeLog"/>
<bean id="after" class="com.szk.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!--配置aop,需要导入aop的约束-->
<aop:config>
<!--切入点-->
<!--pointcut:切入点; expression="execution()固定的样式 execution(要执行的位置 * * * * *)
com.szk.service.UserServiceImpl.*(..))
这个类下的所有方法,有的方法参数可能不同,(..)代表所有的参数个数-->
<aop:pointcut id="pointcut" expression="execution(* com.szk.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="before" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="after" pointcut-ref="pointcut"/>
</aop:config>
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口,应该写UserService,为不是UserServiceImpl实现类
UserService user =context.getBean("user",UserService.class);
user.add();
}
}
2. 方式二:自定义实现AOP【主要是切面定义】
自定义的方法类
public class Diy {
public void before(){
System.out.println("===前===");
}
public void after(){
System.out.println("===后===");
}
}
xml配置
<!--方式二-->
<bean id="diy" class="com.szk.diy.Diy"/>
<aop:config>
<!--自定义切面,ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.szk.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
3.方式三: 使用注解实现
注解类
//标注这个类是一个切面
@Aspect
public class TestZhuJie {
@Before("execution(* com.szk.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("*****前");
}
@After("execution(* com.szk.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("*****后");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取切入的点
//ProceedingJoinPoint:连接点
@Around("execution(* com.szk.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pj) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = pj.proceed();
System.out.println("环绕后");
}
}
xml配置
<bean id="test" class="com.szk.diy.TestZhuJie"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
spring整合mybatis
1. 回顾mybatis
1.1 导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Spring</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Spring_10</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--spring操作数据库需要这个包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
1.2实体类
@Data
public class User {
private String name;
private int id;
private String pwd;
}
1.3编写mapper
public interface UserMapper {
public List<User> select();
}
1.4 编写mapper对应的xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.szk.mapper.UserMapper">
<select id="select" resultType="com.szk.pojo.User">
select * from user
</select>
</mapper>
1.5 编写mybatis的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.szk.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/szk?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456789"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/szk/mapper/UserMapper.xml"/>
</mappers>
</configuration>
1.6 测试
import com.szk.mapper.UserMapper;
import com.szk.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
public static void main(String[] args) throws IOException {
String resources ="mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resources);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.select();
for (User user : userList) {
System.out.println(user);
}
}
}
2. 整合实现方式一
2.1 编写数据源、sqlSessionFactory、SqlSessionTemplate等配置
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
我们这里使Spring提供的pBc : org.springframework.jdbc.datasource-->
<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/szk?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456789"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--还可以绑定mybatis的配置文件,甚至可以完全把mybatis的配置文件写在这里-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/szk/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能用构造器注入sqlSessionFactory,因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--把写的实现接口的实现类注入进来-->
<bean id="userMapper" class="com.szk.mapper.UserMapperImpl">
<property name="session" ref="sqlSession"/>
</bean>
2.2 把子配置文件导入到总的配置文件中
<!--该文件相当于总配置文件,通过import导入子配置文件-->
<import resource="spring-dao.xml"/>
<!--把写的实现接口的实现类注入进来-->
<bean id="userMapper" class="com.szk.mapper.UserMapperImpl">
<property name="session" ref="sqlSession"/>
</bean>
2.3 给接口增加一个实现类
public class UserMapperImpl implements UserMapper{
//原来我们所有的操作都用session来执行,现在我们用SqlSessionTemplate
private SqlSessionTemplate session;
public void setSession(SqlSessionTemplate session) {
this.session = session;
}
@Override
public List<User> select() {
UserMapper mapper = session.getMapper(UserMapper.class);
return mapper.select();
}
}
2.4测试
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List<User> userList = userMapper.select();
for (User user : userList) {
System.out.println(user);
}
}
3整合实现方式二(其实方式二只是方式一的简化)
3.1 编写数据源、sqlSessionFactory等配置
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
我们这里使Spring提供的pBc : org.springframework.jdbc.datasource-->
<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/szk?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456789"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--还可以绑定mybatis的配置文件,甚至可以完全把mybatis的配置文件写在这里-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/szk/mapper/*.xml"/>
</bean>
3.2 把子配置文件导入到总的配置文件中
<!--该文件相当于总配置文件,通过import导入子配置文件-->
<import resource="spring-dao.xml"/>
<bean id="userMapper2" class="com.szk.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
3.3 给接口增加一个实现类(这里继承了SqlSessionDaoSupport)
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> select() {
SqlSession sqlSession = getSqlSession();
UserMapper userMapper = sqlSession.getMapper( UserMapper.class);
List<User> userList = userMapper.select();
return userList;
}
}
3.4 测试
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
List<User> userList = userMapper.select();
for (User user : userList) {
System.out.println(user);
}
}
spring事务
spring 事务有两种方式:
-
一种是声明式事务
-
一种是写进代码中的事务(try/catch)
声明式事务的实现
在整合mybatis的基础上spring-dao.xml中需要加入的配置
<!--配置声明式事务-->
<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入,分两步-->
<!--1、配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManger">
<tx:attributes>
<!--2、给要使用事务的方法配置事务-->
<!--配置事务的传播特性propagation(传播) 默认为REQUIRED-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.szk.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
mapper中添加两个方法,一个添加,一个删除,同时在impl中添加这两个方法的实现
public interface UserMapper {
public List<User> select();
public int add(User user);
public int delete(int id);
}
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> select() {
User user = new User("小王", 3, "333");
SqlSession sqlSession = getSqlSession();
UserMapper userMapper = sqlSession.getMapper( UserMapper.class);
userMapper.add(user);
userMapper.delete(1);
List<User> userList = userMapper.select();
return userList;
}
@Override
public int add(User user) {
return getSqlSession().getMapper(UserMapper.class).add(user);
}
@Override
public int delete(int id) {
return getSqlSession().getMapper(UserMapper.class).delete(id);
}
}
在mapper的xml中写sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.szk.mapper.UserMapper">
<select id="select" resultType="com.szk.pojo.User">
select * from user
</select>
<insert id="add" parameterType="User">
insert into user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
<delete id="delete" parameterType="int">
delete from user where id =#{id}
</delete>
</mapper>
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List<User> userList = userMapper.select();
for (User user : userList) {
System.out.println(user);
}
}
}