Spring常用依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>

Spring常用注解

  • @Autowired:根据bean属性id自动装配
  • @Qualifier:(value = “cat111”)在复杂bean情况下根据value的值选择对应beanid自动装配
  • @Resource:根据id和属性类型匹配 java原生注解
  • Component:组件,放在类上,说明被spring管理了,等效于bean 1.dao [@Repository] 2.service [@Service] 3.controller [@Controller] 组件的延伸用法
  • @Configuration 配置类,等效于beans.xml 代表被容器托管
  • @Bean 注册一个bean,等效于在xml中写一个bean标签,方法的名字等于bean标签中的id,方法的返回值等于bean标签中的class

xml与注解

xml用来管理bean
注解完成属性的注入
要开启注解支持

1
2
3
<!--指定要扫描的包,这个包下的注解生效-->
<context:component-scan base-package="com.zzh.pojo"/>
<context:annotation-config/>

整合Spring Mybatis

1、编写数据源配置

1
2
3
4
5
6
<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?characterEncoding=utf-8&amp;useSSL=false&amp;useUnicode=true&amp;autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

2、sqlSessionFactory
1
2
3
4
5
6
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/zzh/mapper/*.xml"/>
</bean>

3、sqlSessionTemplate
1
2
3
4
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能使用构造器注入sqlSessionFactory-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

4、需要给接口加实现类
5、将自己的写实现类,注册到spring
1
2
3
<bean id="userMapper" class="com.zzh.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>

6、测试

spring中的事务管理

声明式事务:AOP
编程式事务:需要在代码中,进行事务的管理。 Try Catch回滚