Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。
2002,首次推出了Spring框架的雏形: interface21框架
Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版。
spring目的:解决企业应用开发的复杂性
SSH:Struct2 + Spring + Hibernate(全自动的持久化框架)
SSM:SpringMVC + Spring + Mybatis(半自动的持久化框架)
官网:https://spring.io/
官方下载地址:https://repo.spring.io/ui/native/release/org/springframework/spring
GitHub:https://github.com/spring-projects/spring-framework
导入maven依赖
<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>
程序主动创建对象
接口UserDao
public interface UserDao { public void getUser(); }
实现类UserDaoImpl
public class UserDaoImpl implements UserDao{ public void getUser(){ System.out.println("默认获取用户的数据"); } }
业务接口UserService
public interface UserService { void getUser(); }
业务实现类UserServiceImpl
public class UserServiceImpl implements UserService{ private UserDao userDao = new UserDaoImpl(); @Override public void getUser() { userDao.getUser(); } }
测试类MyTest
public class MyTest { public static void main(String[] args) { //用户实际调用的是业务层,不需要接触dao层 UserServiceImpl userService = new UserServiceImpl(); userService.getUser(); } }
修改:将主动权在用户手上
x修改UserServiceImpl,其他不变
public class UserServiceImpl implements UserService{ private UserDao userDao; //利用set进行动态实现值的注入 public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void getUser() { userDao.getUser(); } }
测试类
public class MyTest { public static void main(String[] args) { //用户实际调用的是业务层,不需要接触dao层 UserServiceImpl userService = new UserServiceImpl(); userService.setUserDao(new UserDaoMysqlImpl()); userService.getUser(); } }
总结
IOC本质
在上面标题2中代码的基础上,新增配置文件beans.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"> <!--使用Spring来创建对象,在Spring里成为Bean 类型 变量名 = new 类型(); Hello hello = new Hello(); id = 变量名 class = new 的对象 property 想当于给对象中的属性设置一个值 --> <bean id="userImpl" class="com.ping.dao.UserDaoImpl"/> <bean id="mysqlImpl" class="com.ping.dao.UserDaoMysqlImpl"/> <bean id="UserServiceImpl" class="com.ping.service.UserServiceImpl"> <!-- ref:引用Spring容器中创建好的对象 value:具体的值,基本数据类型 --> <property name="userDao" ref="userImpl"/> </bean> </beans>
测试类
public class MyTest { public static void main(String[] args) { //获取ApplicationContext,拿到Spring的容器 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl"); userServiceImpl.getUser(); } }
总结
实体类User
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="+name); } }
配置文件beans.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="user" class="com.ping.pojo.User"> <property name="name" value="张三"/> </bean> </beans>
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = (User) context.getBean("user"); user.show(); } }
输出结果
User的无参构造
name=张三
实体类User
public class User { private String name; public User(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("name="+name); } }
配置文件beans.xml中的三种方式
<!--第一种方式:下标赋值--> <bean id="user" class="com.ping.pojo.User"> <constructor-arg index="0" value="李四"/> </bean> <!--第二种方式:通过类型创建,不建议使用--> <bean id = "user" class="com.ping.pojo.User"> <constructor-arg type="java.lang.String" value="王五"/> </bean> <!--第三种方式:直接通过参数名来设置--> <bean id="user" class="com.ping.pojo.User"> <constructor-arg name="name" value="赵六"/> </bean>
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了
配置文件beans.xml
<!--别名:如果添如了别名,可以使用别名获取到这个对象--> <alias name="user" alias="userName"/>
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //User user = (User) context.getBean("user"); User user = (User) context.getBean("userName");//同上 user.show(); } }
配置文件beans.xml
<!-- id:bean的唯一标识符,相当于对象名 class:bean对象对应的全限定名(包名 + 类型) name:也是别名,可以同时取多个别名(分隔符不影响) --> <bean id="us" class="com.ping.pojo.User" name="us1 us2,us3;us4"> <property name="name" value="小明"/> </bean>
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = (User) context.getBean("us"); //User user = (User) context.getBean("us1"); //User user = (User) context.getBean("us2"); //User user = (User) context.getBean("us3"); //User user = (User) context.getBean("us4"); user.show(); } }
这个import,一般用于团队开发使用,可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,可以利用import将所有人的beans.xml合并为一个总的applicationContext.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"> <import resource="beans.xml"/> </beans>
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) context.getBean("user"); user.show(); } }
依赖注入:Set注入
环境搭建
复杂类型Address
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实体类
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 String wife; private Properties info; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } 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 String getWife() { return wife; } public void setWife(String wife) { this.wife = wife; } public Properties getInfo() { return info; } public void setInfo(Properties info) { this.info = info; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", address=" + address.toString() + ", books=" + Arrays.toString(books) + ", hobbies=" + hobbies + ", card=" + card + ", games=" + games + ", wife='" + wife + '\'' + ", info=" + info + '}'; } }
配置文件beans.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="address" class="com.ping.pojo.Address"> <property name="address" value="江苏"/> </bean> <bean id="student" class="com.ping.pojo.Student"> <!--第一种:基本数据类型普通值注入,value--> <property name="name" value="张三"/> <!--第二种:Bean注入,ref--> <property name="address" ref="address"/> <!--数组注入,--> <property name="books"> <array> <value>红楼梦</value> <value>西游记</value> <value>水浒传</value> <value>三国演义</value> </array> </property> <!--List注入--> <property name="hobbies"> <list> <value>听歌</value> <value>编程</value> <value>看电影</value> </list> </property> <!--Map注入--> <property name="card"> <map> <entry key="身份证" value="111111222222333333"/> <entry key="银行卡" value="1231231231231231231"/> </map> </property> <!--Set注入--> <property name="games"> <set> <value>LOL</value> <value>CF</value> <value>DNF</value> </set> </property> <!--NULL值注入--> <property name="wife"> <null/> </property> <!--Properties--> <property name="info"> <props> <prop key="学号">123456789</prop> <prop key="性别">男</prop> <prop key="姓名">小明</prop> <prop key="driver">null</prop> <prop key="url">null</prop> <prop key="username">root</prop> <prop key="password">123456</prop> </props> </property> </bean> </beans>
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.toString()); } }
测试结果
Student{name=‘张三’,
address=Address{address=‘江苏’},
books=[红楼梦, 西游记, 水浒传, 三国演义],
hobbies=[听歌, 编程, 看电影],
card={身份证=111111222222333333, 银行卡=1231231231231231231},
games=[LOL, CF, DNF],
wife=‘null’,
info={学号=123456789, 性别=男, 姓名=小明}
}
可以使用p命名空间和c命名空间进行注入
示例
实体类User
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 + '}'; } }
配置文件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" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--p命名空间注入,可以直接注入属性的值,property--> <bean id="user" class="com.ping.pojo.User" p:name="小明" p:age="18"/> <!--c命名空间注入,通过构造器注入,constructor-arg--> <bean id="user2" class="com.ping.pojo.User" c:name="小天" c:age="19"/> </beans>
测试类(导入junit依赖)
public class MyTest { @Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml"); User user = (User) context.getBean("user"); User user2 = context.getBean("user2", User.class); //不用强转 System.out.println(user); System.out.println(user2); } }
注意点:p命名和c命名空间不能直接使用,需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
单例模式(Sprin默认机制)
<bean id="user" class="com.ping.pojo.User" scope="singleton"/>
原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="user" class="com.ping.pojo.User" scope="prototype"/>
其余的request、session、 application这些个只能在web开发中使用到
环境搭建:一个人有两个宠物
三个实体类People、Cat、Dog
public class People { private Cat cat; private Dog dog; private String name; public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "People{" + "cat=" + cat + ", dog=" + dog + ", name='" + name + '\'' + '}'; } }
public class Cat { public void shout(){ System.out.println("miao"); } }
public class Dog { public void shout(){ System.out.println("wang"); } }
配置文件beans.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="cat" class="com.ping.pojo.Cat"/> <bean id="dag" class="com.ping.pojo.Dog"/> <bean id="people" class="com.ping.pojo.People"> <property name="name" value="张三"/> <property name="cat" ref="cat"/> <property name="dog" ref="dag"/> </bean> </beans>
测试类
public class MyTest { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); People people = context.getBean("people", People.class); people.getCat().shout(); people.getDog().shout(); } }
ByName自动装配,修改配置文件beans.xml
<bean id="cat" class="com.ping.pojo.Cat"/> <bean id="dog" class="com.ping.pojo.Dog"/> <!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid --> <bean id="people" class="com.ping.pojo.People" autowire="byName"> <property name="name" value="张三"/> </bean>
ByType自动装配,修改配置文件beans.xml
<bean class="com.ping.pojo.Cat"/> <bean class="com.ping.pojo.Dog"/> <!-- byType:会自动在容器上下文中查找,和自己对象属性类型相同的beanid --> <bean id="people" class="com.ping.pojo.People" autowire="byType"> <property name="name" value="张三"/> </bean>
小结
jdk1.5支持的注解,Spring2.5支持的注解
使用注解需知
<?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/> <bean id="cat" class="com.ping.pojo.Cat"/> <bean id="dog" class="com.ping.pojo.Dog"/> <bean id="people" class="com.ping.pojo.People" /> </beans>
@Autowired
直接在属性上使用即可,也可以在set方式上使用
//如果显式定义了Autowired 的required属性为false,说明这个对象可以为null,否则不允许为空(一般默认) @Autowired(required = false) private Cat cat; @Autowired private Dog dog; ......
使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC (Spring)容器中存在,且符合名字byname
@Autowired是默认通过byType的方式,当匹配到多个同类型时,使用ByName进行装配
@Nullable
@Qualifier(value=“xxx”)
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用**@Qualifier(value=“xxx”)**去配置@Autowired的使用,指定一个唯一的bean对象注入
修改配置 文件beans.xml
<bean id="cat2" class="com.ping.pojo.Cat"/>
实体类people
@Autowired @Qualifier(value="cat2") private Cat cat; ......
@Resource
java中的自动装配注解:import javax.annotation.Resource;
实体类people
@Resource(name = "cat2") private Cat cat;
小结:@Resource和@ Autowired的区别:
在Spring4之后,要使用注解开发,必须要保证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:component-scan base-package="com.ping.pojo"/> <context:annotation-config/> </beans>
实体类User
public class User { public String name = "张三"; }
测试类
public class MyTest { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) context.getBean("user"); System.out.println(user.name); } }
实体类User(使用注解**@Component** 组件)
@Component //相当于<bean id="user" class="com.ping.pojo.User"/> public class User { public String name = "张三"; }
实体类User(@Value(" "))
@Component public class User { @Value("张三") //相当于<property name="name" value="张三"/> public String name; }
或者
@Component public class User { public String name; @Value("张三") //相当于<property name="name" value="张三"/> public void setName(String name) { this.name = name; } }
实体类User
@Component //单例模式 @Scope("singleton") public class User { @Value("张三") //相当于<property name="name" value="张三"/> public String name; }
现在要完全不使用Spring的xml配置了,全权交给Java来做
JavaConfig 是Spring的一个子项目,在Spring 4之后,它成为了一个核心功能
配置文件MyConfig(类)
@Configuration //这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component //@Configuration代表这是一个配置类,相当于beans.xml @ComponentScan("com.ping.pojo") //包扫描 public class MyConfig { @Bean //注册一个bean .就相当于一个bean标签, //这个方法的名宁,就和当于bean标签中的id属性 //这个方法的返回值,就相当于bean标签中的cLass网性 public User user() { return new User(); } }
实体类User
//@Component //功能与MyConfig中的注解@Configuration重合,可不用 //这个注解的意思,就是说明这个类被spring接管了,注册到了容器中 public class User { @Value("张三") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
测试类
public class MyTest { @Test public void test(){ //如果完全使用了配置类方式去做,就只能通过AnnotationConfig 上下文来获取容器,通过配置类的class对象加载 ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User getUser = (User) context.getBean("user"); System.out.println(getUser.getName()); } }
注意:
角色分析:
代理模式的好处:
缺点
代码步骤
接口
//租房 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(); fee(); } //看房 public void seeHouse(){ System.out.println("中介带你看房"); } //签租赁合同 public void hetong(){ System.out.println("签租赁合同"); } //收中介费 public void fee(){ System.out.println("收中介费"); } }
客户访问代理角色
public class Client { public static void main(String[] args) { Host host = new Host(); //代理 Proxy proxy = new Proxy(host); proxy.rent(); } }
动态代理和静态代理角色一样
动态代理的代理类是动态生成的,不是直接写好的
动态代理分为两大类:基于接口的动态代理,基于类的动态代理。
需要了解两个类:
动态代理的好处
代码
类ProxyInvocationhandler
//使用这个类,自动生成代理类 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+"方法"); } }
类Client
public class Client { public static void main(String[] args) { //真实角色 UserServiceImpl userService = new UserServiceImpl(); //代理角色,不存在 ProxyInvocationhandler pih = new ProxyInvocationhandler(); pih.setTarget(userService);//设置要代理的对象 //动态生成代理类 UserService proxy = (UserService) pih.getProxy(); proxy.add(); } }
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice
即Aop在不改变原有代码的情况下,可以增加新的功能
【重点】使用AOP织入,需要导入一个依赖包!
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency>
方式一:使用Spring的API接口【主要SpringAPI接口实现】
接口UserService
public interface UserService { public void add(); public void delete(); public void update(); public void select(); }
类UserServiceImpl
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("查询了一个用户"); } }
前置日志类Log
//前置日志 public class Log implements MethodBeforeAdvice { @Override //method:要执行的目标对象的方法 //args:参数 //target:目标对象 public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了"); } }
后置日志类AfterLog
//后置日志 public class AfterLog implements AfterReturningAdvice { @Override //returnValue:返回值 public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue); } }
配置文件applictionContext.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--> <bean id="userService" class="com.ping.service.UserServiceImpl"/> <bean id="log" class="com.ping.log.Log"/> <bean id="afterLog" class="com.ping.log.AfterLog"/> <!--方式一:使用原生Spring API接口--> <!--配置aop:需要导入aop的约束--> <aop:config> <!--切入点:expression:表达式,execution(要执行的位置),(..)两个点代表可以有任意个参数--> <aop:pointcut id="pointcut" expression="execution(* com.ping.service.UserServiceImpl.*(..))"/> <!--执行环绕增加--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //动态代理代理的是接口 UserService userService = (UserService) context.getBean("userService"); userService.add(); } }
测试结果
方式二:自定义类实现AOP【主要是切面定义】
自定义DiyPointCut
public class DiyPointCut { public void before(){ System.out.println("==========方法执行前========="); } public void after(){ System.out.println("==========方法执行后========="); } }
配置文件applictionContext.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--> <bean id="userService" class="com.ping.service.UserServiceImpl"/> <bean id="log" class="com.ping.log.Log"/> <bean id="afterLog" class="com.ping.log.AfterLog"/> <!--方式二:自定义类--> <bean id="diy" class="com.ping.diy.DiyPointCut"/> <aop:config> <!--自定义切面,ref 要引入的类--> <aop:aspect ref="diy"> <!--切入点:--> <aop:pointcut id="point" expression="execution(* com.ping.service.UserServiceImpl.*(..))"/> <!--通知--> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config> </beans>
测试类同方式一
测试结果
方式三:使用注解实现
自定义类AnnotationPointCut
//方式三:使用注解方式实现AOP @Aspect //标注这个类是一个切面 public class AnnotationPointCut { @Before("execution(* com.ping.service.UserServiceImpl.*(..))") public void before(){ System.out.println("----------方法执行前----------"); } @After("execution(* com.ping.service.UserServiceImpl.*(..))") public void after(){ System.out.println("----------方法执行后----------"); } //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点; @Around("execution(* com.ping.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint jp) throws Throwable { System.out.println("环绕前"); Signature signature = jp.getSignature();//获得签名 System.out.println("signature:"+signature); Object proceed = jp.proceed(); //执行方法 System.out.println("环绕后"); } }
配置文件applictionContext.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--> <bean id="userService" class="com.ping.service.UserServiceImpl"/> <bean id="log" class="com.ping.log.Log"/> <bean id="afterLog" class="com.ping.log.AfterLog"/> <!--方式三:使用注解--> <bean id="annotationPointCut" class="com.ping.diy.AnnotationPointCut"/> <!--开启注解支持,JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")--> <aop:aspectj-autoproxy proxy-target-class="false"/> </beans>
测试类同方式一
测试结果
导入相关jar包
junit
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
mysql数据库
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
mybatis
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
spring相关的
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
aop织入
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency>
mybatis-spring 【new】
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency>
lombok
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency>
编写配置文件
测试
编写工具类MybatisUtils
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis的第一步:获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
编写实体类User
@Data public class User { private int id; private String name; private String pwd; }
编写核心配置文件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核心配置文件--> <configuration> <!--直接引入外部配置文件--> <properties resource="db.properties" /> <typeAliases> <package name="com.ping.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper class="com.ping.mapper.UserMapper"/> </mappers> </configuration>
db.properties
driver = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/mybatisnote?useSSL=false&useUnicode=true&characterEncoding=UTF-8 username = root password = 123456
编写接口UserMapper
public interface UserMapper { public List<User> selectUser(); }
编写Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--configuration核心配置文件--> <mapper namespace="com.ping.mapper.UserMapper"> <select id="selectUser" resultType="user"> select * from user; </select> </mapper>
测试类MyTest
public class MyTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.selectUser(); for (User user : userList) { System.out.println(user); } sqlSession.close(); } }
新建spring-dao.xml编写数据源配置,同时删除mybatis-config.xml中的environments
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid 这里使川Spring提供的JDBC : 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/mybatisnote?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean>
【spring-dao.xml】sqlSessionFactory,可以替换工具类MybatisUtils(可删除)
<!--sqlSessionFactory--> <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/ping/mapper/*.xml"/> </bean>
【spring-dao.xml】sqlSessionTemplate
<!--SqlsessionTempLate:就是使用的sqLsession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入sqLsessionFactory,因为它没有set方法--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
需要给接口加实现类UserMapperImpl
public class UserMapperImpl implements UserMapper{ //原来所有的操作,都使用sqlSession , 现在都使用sqlSessionTemplate private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } @Override public List<User> selectUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } }
【spring-dao.xml】将实现类UserMapperImpl,注入到Spring中
<bean id="userMapper" class="com.ping.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean>
测试
public class MyTest { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> userList = userMapper.selectUser(); for (User user : userList) { System.out.println(user); } } }
方式二:SqlSessionDaoSupport(可以简化上述操作
新增UserMapperImpl2
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ @Override public List<User> selectUser() { SqlSession sqlSession = getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); //return getSqlSession().getMapper(UserMapper.class).selectUser(); } }
【spring-dao.xml】将实现类UserMapperImpl2,注入到Spring中
<bean id="userMapper2" class="com.ping.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
测试
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper2", UserMapper.class); List<User> userList = userMapper.selectUser(); for (User user : userList) { System.out.println(user); } }
声明式事务:AOP【spring-dao.xml】
<!--结合AOP实现事务的织入--> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--给哪些方法配置事务--> <!--配置事务的传播特性:propagation 默认为"REQUIRED"--> <tx:attributes> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="delete" propagation="REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <tx:method name="query" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!--配置事务切入--> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* com.ping.mapper.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
编程式事务:需要再代码中,进行事务的管理