Spring 5
狂神说
1. Spring简介
1.1 简介
-
Spring框架 -
2002年,Rod Jahnson首次推出interface21框架 ——Spring雏形 -
Spring:使现有技术更加使用,可以整合现有的框架技术 -
相关资料:
-
依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
1.2 优点
Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器/框架。
- Spring是一个开源免费的框架、容器;
- Spring是一个轻量级的框架,非入侵式的;
- 控制反转(IOC)、面向切面(AOP);
- 对事务的支持,对框架的支持
1.3 组成
1.4 拓展
2. IOC理论
2.1 简单推导
2.1.1 原来的业务实现
-
Dao层 UserDao.java public interface UserDao {
void getUserInfo();
}
UserDaoImpl.java public class UserDaoImpl implements UserDao{
public void getUserInfo() {
System.out.println("默认数据库获取用户数据!");
}
}
-
Service层 UserService.java public interface UserService {
void getUserInfo();
}
UserServiceImpl.java import com.ano.dao.UserDao;
import com.ano.dao.UserDaoImpl;
import com.ano.dao.UserDaoImplByMysql;
import com.ano.dao.UserDaoImplByOracle;
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImplByOracle();
public void getUserInfo() {
userDao.getUserInfo();
}
}
-
测试 用户调用Service层; 如果用户需求变化,如通过其他数据库获取数据;如MySql、Oracle等,那么需要新增类实现UserDao接口,如下: UserDaoImplByMysql.java public class UserDaoImplByMysql implements UserDao{
public void getUserInfo() {
System.out.println("Mysql数据库获取用户数据!");
}
}
UserDaoImplByOracle.java public class UserDaoImplByOracle implements UserDao{
public void getUserInfo() {
System.out.println("Oracle数据库获取用户数据!");
}
}
但是!为了满足用户需求的改变,还需要去修改Serveice层代码,如下: public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImplByOracle();
public void getUserInfo() {
userDao.getUserInfo();
}
}
-
存在的问题: 用户的需求改变 ,影响到原来的代码实现,必须修改代码;如果代码量十分大,那么维护代码代价非常昂贵!
2.1.2 使用Set方法进行动态注入解决问题
-
解决上述问题,只需要修改Service层代码,如下: UserServiceImpl.java public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void getUserInfo() {
userDao.getUserInfo();
}
}
-
测试 用户只需要根据需求调用Service层时,选择对应的Service实现对象,如下: public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoImplByOracle());
userService.getUserInfo();
}
2.1.3 控制反转思想
- 以上的举例推导,是使用Set接口实现,进行动态实现值的注入,将程序的主动性/控制权转移给用户,程序变成被动地接收对象!
- 这就是控制反转IoC思想!
- 控制反转思想,从本质上解决了问题:开发人员不用去管理对象的创建。大大降低了系统的耦合性,我们只需要专注在业务层的实现上即可。——IoC原型!
2.2 本质
- **控制反转,Inversion of Control (IoC)**是一种设计思想;
- 依赖注入,Dependency Injection (DI) 是实现IoC的一种方法;
- 面向对象编程时,在没有IoC的程序中,对象的创建与对象间的依赖关系完全是硬编程在程序中,对象的创建由程序控制;使用IoC后,将对象的创建转移给了第三方,其本质就是:获取依赖对象的方式反转了。
- 采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式就可以把二者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的;
- IoC是一种使用描述(XML或注解)并通过第三方去生产或者获取特定对象的方式;
- 在Spring中实现IoC的是IoC容器,其实现方式是DI。
3. HelloSpring
3.1 代码示例
-
创建maven工程,导包; -
编写一个实体类; Hello.java 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 + "'}";
}
}
-
编写xml配置文件; application.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="hello" class="com.ano.pojo.Hello">
<property name="str" value="SpringHello"></property>
</bean>
</beans>
-
测试 import com.ano.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello);
}
}
3.2 小结一下
- 对象是由Spring创建的;对象的属性是由Spring容器设置的;
- 这个过程就成为控制反转:
- 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,而使用Spring后,对象是由Spring容器来创建的;
- 反转:程序本身不创建对象了,变成了被动接收对象;
- 依赖注入:本质就是利用set方法进行注入的;
- 所谓IoC,即对象由Spring创建、管理、装配!
- 因此,我们彻底不需要在程序中改动了,要实现不同需求的操作,只需要在xml配置文件中进行修改配置即可。
3.3 上一个案例
-
xml配置文件,只需要在配置里指定属性 application.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="mysqlImpl" class="com.ano.pojo.UserDaoImplByMysql"></bean>
<bean id="oracleImpl" class="com.ano.pojo.UserDaoImplByOracle"></bean>
<bean id="userServiceImpl" class="com.ano.service.UserServiceImpl">
<property name="userDao" ref="oracleImpl"></property>
</bean>
</beans>
-
测试 public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserService userService = (UserService) context.getBean("userServiceImpl");
userService.getUserInfo();
}
?
4. IoC创建对象的方式
4.1 使用无参构造创建对象(默认的)
-
创建User类,并显示声明无参构造 User.java public class User {
private String name;
public User() {
System.out.println("User无参构造被创建!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + this.name);
}
}
-
xml配置文件application.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="user" class="com.ano.pojo.User">
<property name="name" value="AnoBabe"></property>
</bean>
</beans>
-
测试 public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
User user = (User) context.getBean("user");
user.show();
}
结果: User无参构造被创建!
name=AnoBabe
-
如果干掉无参构造,即写一个有参构造函数,配置文件会报错,测试程序也会报初始化失败;
public User(String name) {
this.name = name;
}
4.2 使用有参构造创建对象
-
方式一:下标赋值 创建一个实体类UserTwo.java ,并编写一个有参构造 public class UserTwo {
public UserTwo(String name) {
this.name = name;
System.out.println("UserTwo有参构造被创建");
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + this.name);
}
}
编写配置文件application.xml 配置属性 <bean id="user2" class="com.ano.pojo.UserTwo">
<constructor-arg index="0" value="Ano2222"></constructor-arg>
</bean>
测试: public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserTwo user = (UserTwo) context.getBean("user2");
user.show();
}
结果: User无参构造被创建!
UserTwo有参构造被创建
name=Ano2222
-
方式二:参数类型匹配赋值(不建议使用) 修改配置文件application.xml 配置属性 <bean id="user2" class="com.ano.pojo.UserTwo">
<constructor-arg type="java.lang.String" value="Anohhhhhhh"></constructor-arg>
</bean>
测试: User无参构造被创建!
UserTwo有参构造被创建
name=Anohhhhhhh
-
方式三:引用参数名赋值 修改配置文件application.xml 配置属性 <bean id="user2" class="com.ano.pojo.UserTwo">
<constructor-arg name="name" value="Anoyyyyy"></constructor-arg>
</bean>
测试: User无参构造被创建!
UserTwo有参构造被创建
name=Anoyyyyy
-
小结: 注意测试结果,只要在配置文件中注册bean的,在配置文件加载的时候,容器中管理的所有对象就已经初始化了。
5. Spring配置说明
5.1 别名
5.2 Bean的配置
id :bean的唯一标识符,相当于变量名/对象名class : bean对象所对应的全限定名name :也是别名,bean的别名,可以取多个别名,使用空格、逗号、分号分割取多个别名
5.3 import
6. 依赖注入DI
6.1 构造器注入
6.2 Set方式注入
-
搭建工程; -
编写实体类: Address.java public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
Student.java public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String, String> card;
private Set<String> games;
private Properties info;
private String wife;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address.toString();
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbies=" + hobbies +
", card=" + card +
", games=" + games +
", info=" + info +
", wife='" + wife + '\'' +
'}';
}
}
-
编写xml配置文件,注意不同类型的注入方式 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<beans>
<bean id="address" class="com.ano.pojo.Address">
<property name="address" value="Xi'an"></property>
</bean>
<bean id="student" class="com.ano.pojo.Student">
<property name="name" value="AnoBabe"></property>
<property name="address" ref="address"></property>
<property name="books">
<array>
<value>Java编程思想</value>
<value>数据结构与算法</value>
<value>Effective Java</value>
</array>
</property>
<property name="hobbies">
<list>
<value>看书</value>
<value>游泳</value>
</list>
</property>
<property name="card">
<map>
<entry key="身份证" value="610111111111111111"></entry>
<entry key="银行卡" value="621722222222222222"></entry>
</map>
</property>
<property name="games">
<set>
<value>Nikki</value>
<value>Nikki</value>
<value>LOL</value>
</set>
</property>
<property name="info">
<props>
<prop key="gender">1</prop>
<prop key="age">16</prop>
</props>
</property>
<property name="wife">
<null></null>
</property>
</bean>
</beans>
</beans>
-
测试 public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
-
测试结果: Student{name='AnoBabe', address=Address{address='Xi'an'}, books=[Java编程思想, 数据结构与算法, Effective Java], hobbies=[看书, 游泳], card={身份证=610111111111111111, 银行卡=621722222222222222}, games=[Nikki, LOL], info={age=16, gender=1}, wife='null'}
6.3 拓展方式注入
-
实体类User.java public class User {
private String name;
private int age;
public User(){
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
6.3.1 p-namespace注入
-
编写xml配置文件userBean.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.ano.pojo.User" p:name="Ano" p:age="17"></bean>
</beans>
-
测试 @Test
public void testUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
}
-
测试结果: User{name='Ano', age=17}
6.3.2 c-namespace注入
-
编写xml配置文件userBean.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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user2" class="com.ano.pojo.User" c:name="Top" c:age="19"></bean>
</beans>
-
测试: @Test
public void testUser2() {
ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
-
测试结果 User{name='Top', age=19}
6.4 Bean的作用域
6.4.1 The Singleton Scope
-
单例模式; -
Spring的默认机制; -
显式声明如下: <bean id="user" class="com.ano.pojo.User" p:name="Ano" p:age="17" scope="singleton"></bean>
-
测试 public void testUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user == user2);
}
6.4.2 The Prototype Scope
-
原型模式; -
每次从容器中getBean的时候,都会产生一个新的对象; -
示例如下: <bean id="user" class="com.ano.pojo.User" p:name="Ano" p:age="17" scope="prototype"></bean>
-
测试 public void testUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user == user2);
}
7. Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式;
- Spring会在上下文中自动寻找,并自动给bean装配属性!
- 在Spring中有三种装配方式:
- 在xml中显式的配置;
- 在Java中显示配置;
- **隐式的自动装配bean。
7.1 测试环境搭建
-
创建Maven工程; -
实体类 Cat.java public class Cat {
public void shout() {
System.out.println("Mao~");
}
}
Dog.java public class Dog {
public void shout() {
System.out.println("Wow~");
}
}
People.java public class People {
private String name;
private Dog dog;
private Cat cat;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", dog=" + dog +
", cat=" + cat +
'}';
}
}
-
编写xml配置文件 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="com.ano.pojo.Dog"></bean>
<bean id="cat" class="com.ano.pojo.Cat"></bean>
<bean id="people" class="com.ano.pojo.People">
<property name="name" value="Top"></property>
<property name="dog" ref="dog"></property>
<property name="cat" ref="cat"></property>
</bean>
</beans>
-
测试
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
People people = context.getBean("people", People.class);
people.getDog().shout();
people.getCat().shout();
}
-
是Spring满足bean依赖的一种方式! -
三种装配方式:
-
Cat Dog shout -
People -
xml
7.2 ByName自动装配
-
autowire="byName" 会在Spring容器上下文中查找,和需要注入的对象属性的set方法的值一致的bean <bean id="dog" class="com.ano.pojo.Dog"></bean>
<bean id="cat" class="com.ano.pojo.Cat"></bean>
<bean id="people" class="com.ano.pojo.People" autowire="byName">
<property name="name" value="Top"></property>
</bean>
7.3 ByType自动装配
-
autowire="byType" 会在Spring容器上下文中查找,和需要注入的对象属性的类型一致的bean <bean id="dog" class="com.ano.pojo.Dog"></bean>
<bean id="cat" class="com.ano.pojo.Cat"></bean>
<bean id="people" class="com.ano.pojo.People" autowire="byType">
<property name="name" value="Top"></property>
</bean>
-
小结:
- byName需要保证所有bean的id唯一并且这个bean和需要注入的对象属性的set方法的值一致;
- byType需要保证所有bean的class唯一,并且这个bean需要注入的对象属性的类型一致;
7.4 使用注解自动装配
7.4.1 @Autowired
- 直接在属性上使用即可,也可以在set方法上使用;
- 如果自动装配的属性bean在IoC容器中存在,那么直接使用
@Autowired ,就不用编写set方法了;
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: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">
<bean id="dog" class="com.ano.pojo.Dog"></bean>
<bean id="dog11" class="com.ano.pojo.Dog"></bean>
<bean id="cat" class="com.ano.pojo.Cat"></bean>
<bean id="cat22" class="com.ano.pojo.Cat"></bean>
<bean id="people" class="com.ano.pojo.People"></bean>
<context:annotation-config/>
</beans>
People.java
public class People {
private String name;
@Autowired
private Dog dog;
@Autowired
private Cat cat;
...
}
-
如果@Autowired 自动装配的环境比较复杂,无法通过一个注解@Autowired 完成时,如以下配置文件,这种情况可以使用注解@Qualifier(value = "xxx") 配合@Autowired ,指定一个唯一的bean对象注入。示例如下: applicationContext.xml <bean id="dog1" class="com.ano.pojo.Dog"></bean>
<bean id="dog11" class="com.ano.pojo.Dog"></bean>
<bean id="cat2" class="com.ano.pojo.Cat"></bean>
<bean id="cat22" class="com.ano.pojo.Cat"></bean>
People.java public class People {
private String name;
@Autowired
@Qualifier(value = "dog1")
private Dog dog;
@Autowired
@Qualifier(value = "cat2")
private Cat cat;
...
}
7.4.2 @Resource
-
Java的注解 javax.annotation.Resource; -
示例 applicationContext.xml <bean id="dog1" class="com.ano.pojo.Dog"></bean>
<bean id="dog11" class="com.ano.pojo.Dog"></bean>
<bean id="cat" class="com.ano.pojo.Cat"></bean>
<bean id="cat22" class="com.ano.pojo.Cat"></bean>
People.java public class People {
private String name;
@Resource(name = "dog1")
private Dog dog;
@Resource
private Cat cat;
...
}
-
@Autowired 和@Resource的区别
- 都是用来自动装配,可以放在属性字段上;
- @Autowired先通过byType的方式实现,如果类对象型不唯一,就使用byName实现,对象类型必须存在;
- @Resource默认先通过byName的方式实现,如果找不到name,则通过byType实现,如果两个都找不到报错;
8. 使用注解开发
-
在Spring4之后,要使用注解开发,必须要保证aop包导入了; -
使用注解还需要导入约束,配置注解的支持 <?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>
8.1 bean
-
applicationContext.xml <context:component-scan base-package="com.ano.pojo"></context:component-scan>
-
User.java package com.ano.pojo;
@Component
public class User {
private String name = "ANOO";
public String getName() {
return name;
}
}
-
@Component 就等价于 <bean id="user" class="com.ano.pojo.User" ></bean>
8.2 属性如何注入
-
User.java package com.ano.pojo;
@Component
public class User {
@Value("ANO")
private String name;
public String getName() {
return name;
}
}
-
@Value("XXX") 相当于中 <bean id="user" class="com.ano.pojo.User" >
<property name="name" value="ANO"></property>
</bean>
-
set方法上注入也可以
8.3 衍生的注解
**【@Component】**有几个衍生注解,在web开发中,会按照MVC三层结构分层:
-
dao层UserDao 【@Repository】 -
service层 【@Service】 -
controller层 【@Controller】
以上四个注解功能一样,代表将某个类注入到Spring中,装配bean
8.4 自动装配的注解
- @Autowired:自动装配通过type、name。如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = “xxx”)去配置。
- @Nullable 字段标记了这个注解,说明这个字段可以为null;
- @Resource:自动装配通过name、type。
8.5 作用域
-
User.java @Component
@Scope("singleton")
public class User {
@Value("ANO")
private String name;
...
}
8.6 小结xml与注解
- xml 更加万能,适用于任何场合,维护简单方便;
- 注解不是自己的类使用不了,维护相对复杂;
- xml与注解的最佳实践是:
- xml用来管理bean;
- 注解只负责完成属性的注入。
9. 使用javaConfig实现配置Spring
- 到这里就可以不使用Spring的xml配置了,全权交给JAVA来做;
- JavaConfig是Spring的子项目,在Spring4之后成为了一个核心功能。
-
实体类User.java public class User {
private String name;
public String getName() {
return name;
}
@Value("ANO")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
-
配置类MyConfig.java
@Configuration
@ComponentScan("com.ano.pojo")
@Import(MyConfig2.class)
public class MyConfig {
@Bean
public User getUser() {
return new User();
}
}
-
测试 public class MyTest {
@Test
public void testAppConfiguration() {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
}
10. 代理模式
10.1 静态代理
角色分析:
10.3 加深理解
-
UserService.java 接口 public interface UserService {
void add();
void delete();
void update();
void query();
}
-
UserServiceImpl.java 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 query() {
System.out.println("查询一个用户");
}
}
-
新需求为:在使用增删改查之前打印日志!为了不改变原有代码,考虑使用代理机制实现 UserServiceProxy.java public class UserServiceProxy implements UserService{
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
@Override
public void add() {
log("add");
userService.add();
}
@Override
public void delete() {
log("delete");
userService.delete();
}
@Override
public void update() {
log("update");
userService.update();
}
@Override
public void query() {
log("query");
userService.query();
}
public void log(String msg) {
System.out.println("【日志】使用了一个" + msg + "方法");
}
}
-
客户端访问 public class Client {
public static void main(String[] args) {
UserServiceProxy userService = new UserServiceProxy();
userService.setUserService(new UserServiceImpl());
userService.add();
userService.delete();
userService.update();
userService.query();
}
}
【日志】使用了一个add方法
增加了一个用户
【日志】使用了一个delete方法
删除了一个用户
【日志】使用了一个update方法
更新了一个用户
【日志】使用了一个query方法
查询一个用户
-
AOP
10.2 动态代理
10.2.1 了解
- 和静态代理角色一样
- 是动态生成的,不是直接写好的
- 动态代理分为两大类:
- 基于接口实现的动态代理 ——JDK动态代理
- 基于类实现的动态代理:cglib
- 目前使用较多的是使用javasist生成动态代理
- 需要了解两个类
- Proxy:代理
- InovactionHandler:调用处理程序,每一个代理实例都需要一个调用处理程序
10.2.2 代码示例
-
抽象角色:接口
public interface Rent {
void rent();
}
-
真实角色
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东出租房子!");
}
}
-
动态代理角色ProxyInvocationHandler.java import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
Object result = method.invoke(rent, args);
charge();
return result;
}
public void seeHouse() {
System.out.println("带客户看房子");
}
public void charge() {
System.out.println("收取中介费");
}
}
-
客户端访问 public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
带客户看房子
房东出租房子!
收取中介费
10.2.3 加深理解
-
可以改写为一个通用的动态代理实现的类 public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String msg) {
System.out.println("【日志】执行了" + msg + "方法");
}
}
-
测试UserService public class Client {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);
UserService user = (UserService) pih.getProxy();
user.add();
user.delete();
user.update();
user.query();
}
}
【日志】执行了add方法
增加了一个用户
【日志】执行了delete方法
删除了一个用户
【日志】执行了update方法
更新了一个用户
【日志】执行了query方法
查询一个用户
10.2.4 动态代理的好处
- 可以使真实角色的操作更加纯粹,不用去关注一些公共业务;
- 公共角色就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
11. AOP
11.1 什么是AOP
- AOP, Aspect Oriented Programming,面向切片编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术;
- AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生泛型;
- 利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率。
11.2 AOP在Spring中的作用
- 提供声明式事务,允许用户自定义切面;
- 一些专业术语:
- 横切关注点: 跨越应用程序多个模块的方法或功能。即,与业务逻辑无关的、但是需要关注的部分就是横切关注点,如日志、安全、缓存、事务等;
- 切面 Aspect:横切关注点被模块化的特殊对象,即是一个类;
- 通知 Advice:切面必须要完成的工作,即是类中的一个方法;
- 目标 Target:被通知的对象;
- 代理 Proxy:向目标对象应用通知之后创建的对象;
- 切入点 Pointcut:切面通知执行的"地点"的定义;
- 连接点 JoinPoint:与切面匹配的执行点。
11.3 使用Spring实现AOP
重点:使用AOP织入,需要导入依赖:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
11.3.1 方法1:使用Spring的API接口实现
-
接口 public interface UserService {
void create();
void read();
void update();
void delete();
}
-
实现类 public class UserServiceImpl implements UserService{
@Override
public void create() {
System.out.println("增加一个用户");
}
@Override
public void read() {
System.out.println("查询一个用户");
}
@Override
public void update() {
System.out.println("修改一个用户");
}
@Override
public void delete() {
System.out.println("删除一个用户");
}
}
-
编写两个增强类 BeforeLog.java 前置增强类 public class BeforeLog implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName() + "的" + method.getName() + "方法被调用了");
}
}
AfterLog.java 后置增强类 public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了" + target.getClass().getName() + "的"
+ method.getName() + "方法, 返回值为:"
+ returnValue );
}
}
-
配置文件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.ano.service.UserServiceImpl"></bean>
<bean id="beforeLog" class="com.ano.log.BeforeLog"></bean>
<bean id="afterLog" class="com.ano.log.AfterLog"></bean>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.ano.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
-
测试 public class MyTest {
@Test
public void testAop() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.create();
userService.read();
userService.update();
userService.delete();
}
}
com.ano.service.UserServiceImpl的create方法被调用了
增加一个用户
执行了com.ano.service.UserServiceImpl的create方法, 返回值为:null
com.ano.service.UserServiceImpl的read方法被调用了
查询一个用户
执行了com.ano.service.UserServiceImpl的read方法, 返回值为:null
com.ano.service.UserServiceImpl的update方法被调用了
修改一个用户
执行了com.ano.service.UserServiceImpl的update方法, 返回值为:null
com.ano.service.UserServiceImpl的delete方法被调用了
删除一个用户
执行了com.ano.service.UserServiceImpl的delete方法, 返回值为:null
11.3.2 方法2:自定义类实现AOP
-
自定义类DiyPointcut.java
public class DiyPointcut {
public void before() {
System.out.println("【日志】执行方法之前");
}
public void after() {
System.out.println("【日志】执行方法之后");
}
}
-
编写配置文件applicationContext.xml <bean id="diy" class="com.ano.diy.DiyPointcut"></bean>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.ano.service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point" ></aop:before>
<aop:after method="after" pointcut-ref="point"></aop:after>
</aop:aspect>
</aop:config>
-
测试 public class MyTest {
@Test
public void testAop() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.create();
}
}
【日志】执行方法之前
增加一个用户
【日志】执行方法之后
11.3.3 方法3:使用注解实现AOP
-
自定义类AnnotationPointcut.java
@Aspect
public class AnnotationPointcut {
@Before("execution(* com.ano.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("【日志】方法执行之前");
}
@After("execution(* com.ano.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("【日志】方法执行之后");
}
@Around("execution(* com.ano.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("【日志】环绕前");
System.out.println("签名:" + jp.getSignature());
Object proceed = jp.proceed();
System.out.println("【日志】环绕后");
System.out.println(proceed);
}
}
-
编写配置文件applicationContext.xml
<bean id="annotationPointcut" class="com.ano.annotation.AnnotationPointcut"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
-
测试 【日志】环绕前
签名:void com.ano.service.UserService.create()
【日志】方法执行之前
增加一个用户
【日志】方法执行之后
【日志】环绕后
null
12. 整合Mybatis
步骤:
- 导入相关包 junit、mysql、mybatis、spring-mvc、spring-jdbc、aspectjweaver、mybatis-spring、lombok…
- 编写配置文件
- 测试
12.1 回忆mybatis
-
新建module,pom.xml中导入相关jar包 <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
-
编写实体类 根据数据库表编写User.java
@Data
public class User {
private int id;
private String name;
private String pwd;
}
UserMapper.java
public interface UserMapper {
List<User> getAllUsers();
}
-
编写核心配置文件 mybatis-config.xml <?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.ano.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/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.ano.mapper.UserMapper"></mapper>
</mappers>
</configuration>
-
编写Mapper文件,UserMapper.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.ano.mapper.UserMapper">
<select id="getAllUsers" resultType="user" >
select * from mybatis.user
</select>
</mapper>
-
测试 @Test
public void testGetAllUsers() throws IOException {
String resource = "mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> allUsers = mapper.getAllUsers();
for (User user : allUsers) {
System.out.println(user);
}
}
User(id=1, name=anobabe, pwd=123456)
User(id=2, name=topppppp, pwd=top)
User(id=3, name=trouble, pwd=987654)
12.2 整合mybatis
12.2.1 方式一
-
导入mybatis-spring包 <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
-
新建类UserMapperImpl.java public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> getAllUsers() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> allUsers = mapper.getAllUsers();
return allUsers;
}
}
-
编写配置文件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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/ano/mapper/*.xml"></property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<bean id="userMapper" class="com.ano.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"></property>
</bean>
</beans>
-
修改mybatis-config.xml <?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.ano.pojo"/>
</typeAliases>
</configuration>
-
测试 @Test
public void testGetAllUsers() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapperImpl mapper = context.getBean("userMapper", UserMapperImpl.class);
List<User> allUsers = mapper.getAllUsers();
for (User user : allUsers) {
System.out.println(user);
}
}
12.2.2 方式二
-
UserMapperImpl2.java public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> getAllUsers() {
return getSqlSession().getMapper(UserMapper.class).getAllUsers();
}
}
-
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/ano/mapper/*.xml"></property>
</bean>
<bean id="userMapper2" class="com.ano.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
-
测试OK @Test
public void testGetAllUsers() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper mapper = context.getBean("userMapper2", UserMapper.class);
List<User> allUsers = mapper.getAllUsers();
for (User user : allUsers) {
System.out.println(user);
}
}
13. 声明式事务
13.1 回顾事务
- 把一组业务当成一个业务来做,要么都成功,要么都失败
- 确保一致性和完整性
- 事务的ACID原则:
- 原子性Atomicity:事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用。
- 一致性Consistency:一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中。
- 隔离性Isolation:可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏。
- 持久性Durability:事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中。
13.2 spring中的事务管理
13.2.1 事务案例
-
搭建环境,拷贝上一节的案例; -
UserMapper.java 中新增两个接口
public int addUser(User user);
public int deleteUser(int id);
-
UserMapper.xml 编写对应xml文件,这里故意先写错delete语句 <insert id="addUser" parameterType="user">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
deletes from mybatis.user where id = #{id}
</delete>
-
编写接口实现类UserMapperImpl.java public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> getAllUsers() {
User user = new User(4, "hhhh", "123456");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(4);
return mapper.getAllUsers();
}
@Override
public int addUser(User user) {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.addUser(user);
}
@Override
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
-
测试 @Test
public void testGetUserList() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapper = context.getBean("userMapper", UserMapper.class);
List<User> allUsers = mapper.getAllUsers();
for (User user : allUsers) {
System.out.println(user);
}
}
结果会报错,因为delete语句写错了,但发现数据库表中数据插入成功。 原因:没有进行事务管理; Spring提供了事务管理,需要配置即可。
13.2.2 Spring的声明式事务管理
Spring中的事务管理支持编程式事务管理和声明式事务管理。
- 编程式事务管理:
- 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点是必须在每个事务操作业务逻辑中包含额外的事务管理代码;
- 声明式事务管理:
- 一般情况下比编程式事务好用;
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理;
- 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
-
配置spring-dao.xml ,注意导入tx约束 <?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"
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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/ano/mapper/*.xml"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="datasource"></constructor-arg>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="datele" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.ano.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>
</beans>
-
再次测试。
|