优点:
1、spring是一个开源的免费的框架(容器)
2、spring是一个轻量级的、非入侵式的框架
3、控制反转(ioc),面向切面编程(aop)
4、支持事务的处理,对框架整合的支持
总结:spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
package com.zhuzhu.pojo;
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 + '\'' +
'}';
}
}
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="hello" class="com.zhuzhu.pojo.Hello">
<property name="str" value="Spring啊哈哈哈哈哈"/>
</bean>
Test :
public class Test01 {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都是在Spring中管理了,我们要使用,就直接去里面取出来就可以了
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
使用无参构造创建对象:
beans.xml
<bean id="user" class="com.zhuzhu.pojo.User">
<property name="name" value="铁柱啊"/>
</bean>
User:
package com.zhuzhu.pojo;
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public void show(){
System.out.println("name===="+name);
}
}
Test:
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都是在Spring中管理了,我们要使用,就直接去里面取出来就可以了
User user = (User) context.getBean("user");
//System.out.println(user.toString());
user.show();
}
有参:
1.下标赋值
User里加个有参构造:
public User(String name){
this.name=name;
}
beans.xml
<bean id="user" class="com.zhuzhu.pojo.User">
<constructor-arg index="0" value="居居宝贝"/>
</bean>
2.通过类型创建
<bean id="user" class="com.zhuzhu.pojo.User">
<constructor-arg type="java.lang.String" value="居居宝贝"/>
</bean>
3.直接通过参数名来设置
<bean id="user" class="com.zhuzhu.pojo.User">
<constructor-arg name="name" value="居居宝贝"/>
</bean>
spring:我们在创建bean的时候他已经帮我们实例化了
总结:在配置文件加载的时候,容器中管理的对象已经初始化了
Spring配置
别名:
<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="user" alias="userNew"/>
Bean的配置:---------------
id:bean的唯一标识符,也就是相当于我们学的对像名
class:bean对象所对应的全限定名:包名+类型
name:也是别名,而且name可以同时取多个别名
可以用空格、分号、逗号、将两个不同名字隔开
import
这个import,一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有的beans合并为一个总的。
applicationContext.xml (总配置)
①:
②:
③:
把上面①、②、③写在总配置里,然后使用的时候就使用总配置就行了
================================================================
依赖注入
1、构造器注入(前面)
2、Set方式注入
依赖注入:Set注入
①依赖:bean对象的创建依赖于容器
②注入:bean对象中所有的属性,由容器来注入
Student类
package com.zhuzhu.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] book;
private List<String> hobbys;
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[] getBook() {
return book;
}
public void setBook(String[] book) {
this.book = book;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
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 +
", book=" + Arrays.toString(book) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
Address类:
package com.zhuzhu.pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
beans.xml
<bean id="address" class="com.zhuzhu.pojo.Address"/>
<bean id="student" class="com.zhuzhu.pojo.Student">
<!-- 第一种:普通值注入,value-->
<property name="name" value="居居大宝贝"/>
</bean>
Test:
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都是在Spring中管理了,我们要使用,就直接去里面取出来就可以了
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
System.out.println(student.getAddress());
}
…
第二种:Bean注入,ref
。
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="hello" class="com.zhuzhu.pojo.Hello">
<property name="str" value="Spring啊哈哈哈哈哈"/>
</bean>-->
<!-- <bean id="user" class="com.zhuzhu.pojo.User">
<property name="name" value="铁柱啊"/>
</bean>-->
<!--<bean id="user" class="com.zhuzhu.pojo.User">
<constructor-arg index="0" value="居居宝贝"/>
</bean>-->
<!-- <bean id="user" class="com.zhuzhu.pojo.User">
<constructor-arg type="java.lang.String" value="居居宝贝"/>
</bean>-->
<!--
<bean id="user" class="com.zhuzhu.pojo.User" name="user2 u2,u3;u4">
<constructor-arg name="name" value="居居宝贝"/>
</bean>
<!–设置别名:在获取Bean的时候可以使用别名获取–>
<alias name="user" alias="userNew"/>
-->
<bean id="address" class="com.zhuzhu.pojo.Address"/>
<bean id="student" class="com.zhuzhu.pojo.Student">
<!-- 第一种:普通值注入,value-->
<property name="name" value="居居大宝贝"/>
<!-- 第二种:Bean注入,ref-->
<property name="address" ref="address"/>
<!-- 数组-->
<property name="book">
<array>
<value>红楼梦</value>
<value>水浒传</value>
<value>西游记</value>
<value>三国演义</value>
</array>
</property>
<!-- List-->
<property name="hobbys">
<list>
<value>学习</value>
<value>打游戏</value>
<value>睡觉</value>
</list>
</property>
<!-- Map-->
<property name="card">
<map>
<entry key="身份证" value="452623199811112222"/>
<entry key="银行卡" value="6228481235266489752"/>
</map>
</property>
<!-- Set-->
<property name="games">
<set>
<value>lol</value>
<value>aa</value>
<value>bb</value>
</set>
</property>
<!-- null-->
<property name="wife">
<null/>
</property>
<!-- info-->
<property name="info">
<props>
<prop key="driver">2020</prop>
<prop key="url">aabb</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
</beans>
===================================
p命名空间(需要无参构造器)
User2:
package com.zhuzhu.pojo;
public class User2 {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User2{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
,
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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间注入,可以直接注入属性的值:property-->
<bean id="user2" class="com.zhuzhu.pojo.User2" p:name="猪猪" p:age="18">
</bean>
Test
public class Test01 {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User2 user2 = (User2) context.getBean("user2");
System.out.println(user2.getAge());
System.out.println(user2.getName());
System.out.println(user2+"111111");
}
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User2 user2 = context.getBean("user2", User2.class);
System.out.println(user2);
}
}
.
c命名空间(需要加一个有参构造器)
加构造器:
.
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"
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">
<!-- c命名空间注入,通过构造器注入:construct-args-->
<bean id="user3" class="com.zhuzhu.pojo.User2" c:age="16" c:name="发财" ></bean>
<!-- p命名空间注入,可以直接注入属性的值:property-->
<bean id="user2" class="com.zhuzhu.pojo.User2" p:name="猪猪" p:age="18">
</bean>
Test:
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User2 user3 = context.getBean("user3", User2.class);
System.out.println(user3);
}
Bean的作用域:
。。。。。。。。。.。。。。。。。。。。
。。。。。。。。
Bean的自动装配
①自动装配是Spring满足bean依赖的一种方式
②Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
1、在xml中显示的配置
2、在Java中显示的配置
3、隐式的自动装配bean
ref="" --------引入
Cat:
public class Cat {
public void shout(){
System.out.println("miao miao");
}
}
Dog:
public void shout(){
System.out.println("狗子");
}
People:
package com.zhuzhu.pojo;
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 + '\'' +
'}';
}
}
Test:
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都是在Spring中管理了,我们要使用,就直接去里面取出来就可以了
People people = context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
----byName自动装配:
beans.xml
<bean id="cat" class="com.zhuzhu.pojo.Cat"/>
<bean id="dog" class="com.zhuzhu.pojo.Dog"/>
<!-- byName会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid-->
<bean id="people" class="com.zhuzhu.pojo.People" autowire="byName">
<property name="name" value="猪猪"/>
</bean>
。
。
。
-----byType自动装配:
beans.xml
<bean id="cat" class="com.zhuzhu.pojo.Cat"/>
<bean id="ssdog" class="com.zhuzhu.pojo.Dog"/>
<!-- byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean-->
<bean id="people" class="com.zhuzhu.pojo.People" autowire="byType">
<property name="name" value="猪猪"/>
</bean>
.
小结:
byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
========================================================================================================
使用注解实习自动装配
要使用注解须知:
1、导入约束:context约束
2、配置注解的支持:context:annotation-config/
People:
.
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解的支持-->
<context:annotation-config/>
<bean id="cat" class="com.zhuzhu.pojo.Cat"/>
<bean id="dog" class="com.zhuzhu.pojo.Dog"/>
<bean id="people" class="com.zhuzhu.pojo.People"/>
</beans>
.
Test:
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
.
@Autowired
直接在属性上使用即可,也可以在set方式上使用
使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName
@Nullable 字段标记这个注解,说明这个字段可以为null
.
.
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
…
使用注解开发
。
1、bean
2、属性如何注入
3、衍生的注解
4、自动装配
5、作用域
6、小结
在spring4之后,要使用注解开发,必须要保证aop的包导入了
@Component:组件,放在类上,说明这个类被spring管理了,就是bean!
1、bean
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.zhuzhu.pojo"/>
<!--开启注解的支持-->
<context:annotation-config/>
</beans>
.
User:
import org.springframework.stereotype.Component;
//等价于<bean id="user" class="com.zhuzhu.pojo.User"/> @Component 组件
@Component
public class User {
public String name="铁柱小伙汁";
}
Test:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
System.out.println(user.name);
}
…
…
.
2、属性如何注入
//等价于<bean id="user" class="com.zhuzhu.pojo.User"/> @Component 组件
@Component
public class User {
//相当于<property name="name" value="铁柱靓仔"/>
@Value("铁柱靓仔")
public String name;
}
.
//等价于<bean id="user" class="com.zhuzhu.pojo.User"/> @Component 组件
@Component
public class User {
/*//相当于<property name="name" value="铁柱靓仔"/>
@Value("铁柱靓仔")*/
public String name;
@Value("铁柱靓仔")
public void setName(String name) {
this.name = name;
}
}
…
.
3、衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层
。dao(@Repository)
。service(@Service)
。controller(@Controller)
这四个注解功能都是一样的 ,都是代表将某个类注册到Spring中,装配Bean
4、自动装配
@Aurowired:自动装配通过类型。名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(valur=“xxx”)
@Nullable 字段标记了这个注解,说明这个字段可以为null
@Resource :自动装配通过名字。类型
。
。
5、作用域
。
6.小结:xml与注解:
。xml更加万能,适用于任何场合,维护简单方便
。注解不是自己类使用不了,维护相对复杂
xm与注解最佳实践:
。xml用来管理bean;
。注解只负责完成属性的注入
。我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.zhuzhu.pojo"/>
<!--开启注解的支持-->
<context:annotation-config/>
=======================================
使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能
。
User
package com.zhuzhu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("富贵小伙子") //属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
。
ZhuzhuConfig
package com.zhuzhu.config;
import com.zhuzhu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前的beans.xml一样
@Configuration
@ComponentScan("com.zhuzhu.pojo") //扫描包
public class ZhuzhuConfig {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象
}
}
.
Test
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ZhuzhuConfig.class);
User getUser = (User) context.getBean("getUser");//括号里写的是ZhuzhuConfig里的方法名
System.out.println(getUser.getName());
}
.
.
多个配置类:
@Configuration
public class Config01 {
}
。
==========================
代理模式
代理模式是springAOP的底层
代理模式的分类:
.静态代理
动态代理
/
。
/
代码步骤:
1、接口
//租房
public interface Rent {
public void rent();
}
2、真实角色
//房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
}
3、代理角色
//中介
public class Proxy implements Rent{
private Host host;
public Proxy(Host host) {
this.host = host;
}
public Proxy() {
}
public void rent() {
host.rent();
seeHouse();
hetong();
fare();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//看房
public void hetong(){
System.out.println("签租赁合同");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
}
4、客户端访问代理角色
//我
public class Client {
public static void main(String[] args) {
/* Host host = new Host();
host.rent();*/
//房东要出租房子
Host host = new Host();
//代理,中介帮房东租房子,但是,代理一般都会有一些附属操作
Proxy proxy = new Proxy(host);
proxy.rent();//你不用面对房东,直接找中介租房即可
}
}
。
。
—加深对代理模式的理解
。
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
//真实对象
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void query() {
System.out.println("查询了一个用户");
}
}
package com.zhuzhu.demo02;
public class UserServiceProxy implements UserService {
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
private UserServiceImpl userService;
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.add();
}
public void update() {
log("update");
userService.add();
}
public void query() {
log("query");
userService.add();
}
//日志方法
public void log(String msg){
System.out.println("使用了"+msg+"方法");
}
}
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.query();
}
}
。
。
。
。。。。。。。。。
package com.zhuzhu.demo03;
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);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
seeHouse();
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介带看房子---");
}
public void fare(){
System.out.println("收中介费---");
}
}
package com.zhuzhu.demo03;
//房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
}
package com.zhuzhu.demo03;
//租房
public interface Rent {
public void rent();
}
package com.zhuzhu.demo03;
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是动态生成的,我们并没有写
proxy.rent();
}
}
。。
。
package com.zhuzhu.demo04;
import com.zhuzhu.demo03.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//等会我们会用这个类,自动生成代理类
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);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(target, args);
return result;
}
}
。
package com.zhuzhu.demo04;
import com.zhuzhu.demo02.UserService;
import com.zhuzhu.demo02.UserServiceImpl;
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
。
。
.
.
.
使用spring实现aop
使用aop,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
方式一:使用spring的api接口(主要springAPI接口实现)
.
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回结果为"+returnValue);
}
}
.
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.zhuzhu.service.UserServiceImpl"/>
<bean id="log" class="com.zhuzhu.log.Log"/>
<bean id="afterLog" class="com.zhuzhu.log.AfterLog"/>
<!--方式一:使用原生spring api接口-->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式 execution(要执行的位置***)-->
<aop:pointcut id="pointcut" expression="execution(* com.zhuzhu.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
.
public class Test1 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
。。
。
二:自定义来实现aop(主要是切面定义)
<!--方式二:自定义类-->
<bean id="diy" class="com.zhuzhu.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面,ref 要引用的类-->
<aop:aspect ref="diy">
<!-- 切入点-->
<aop:pointcut id="point" expression="execution(* com.zhuzhu.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
package com.zhuzhu.diy;
public class DiyPointCut {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
。
package com.zhuzhu.diy;
//方式三:使用注解方式实现aop
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.zhuzhu.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行前");
}
@After("execution(* com.zhuzhu.service.UserServiceImpl.*(..))")
public void After(){
System.out.println("方法执行后");
}
}
<!--方式三-->
<bean id="annotationPointCut" class="com.zhuzhu.diy.AnnotationPointCut"/>
<!--开启注解支持!-->
<aop:aspectj-autoproxy/>
。