1、IOC
1、概念及原理
1.1IOC概念
依赖:指Bean对象的创建依赖于容器
注入:指Bean对象所依赖的资源,由容器来设置和装配
1.2IOC原理
使用工厂模式读取xml配置文件(也可以是基于注解),通过反射的方式创建对象。
2、DI依赖注入的三种方式
2.1构造器注入
public class Dog {
private String name;
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+ name );
}
public Dog(String name) {
this.name = name;
}
}
<?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.hpu.entity.Dog">
<constructor-arg name="name" value="旺财"/>
</bean>
</beans>
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext con = new ClassPathXmlApplicationContext("dog.xml");
Dog dog = con.getBean("dog", Dog.class);
dog.show();
}
}
输出
name=旺财
2.2set注入
要求被注入的属性必须有set方法
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public void setName(String name) {
this.name = name;
}
public void setAddress(Address address) {
this.address = address;
}
public void setBooks(String[] books) {
this.books = books;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public void setGames(Set<String> games) {
this.games = games;
}
public void setWife(String wife) {
this.wife = wife;
}
public void setInfo(Properties info) {
this.info = info;
}
public void show(){
System.out.println("name="+ name
+ ",address="+ address.getAddress()
+ ",books="
);
for (String book:books){
System.out.print("<<"+book+">>\t");
}
System.out.println("\n爱好:"+hobbys);
System.out.println("card:"+card);
System.out.println("games:"+games);
System.out.println("wife:"+wife);
System.out.println("info:"+info);
}
}
<?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="addr" class="com.hpu.entity.Address">
<property name="address" value="重庆"/>
</bean>
<bean id="student" class="com.hpu.entity.Student">
<!--常量注入-->
<property name="name" value="小明"/>
<!--Bean注入-->
<property name="address" ref="addr"/>
<!--数组注入-->
<property name="books">
<array>
<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="456456456465456"/>
<entry key="建设" value="1456682255511"/>
</map>
</property>
<!--set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
<!--null注入-->
<property name="wife"><null/></property>
<!--property注入-->
<property name="info">
<props>
<prop key="学号">20190604</prop>
<prop key="性别">男</prop>
<prop key="姓名">小明</prop>
</props>
</property>
</bean>
</beans>
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext con = new ClassPathXmlApplicationContext("stu.xml");
Student student = con.getBean("student", Student.class);
student.show();
}
}
输出
name=小明,address=重庆,books=
<<西游记>> <<红楼梦>> <<水浒传>>
爱好:[听歌, 看电影, 爬山]
card:{中国邮政=456456456465456, 建设=1456682255511}
games:[LOL, BOB, COC]
wife:null
info:{学号=20190604, 性别=男, 姓名=小明}
2.3其他注入(p命名空间和c命名空间注入)
使用前均需导入相关的依赖
p命名空间基于set方法
c命名空间基于构造器
3、Bean的作用域
在Spring中,那些组成应用程序的主体及由Sping IOC容器所管理的对象,被称之为Bean。简单来说,bean就是由IOC容器初始化,装配及管理的对象。
3.1Singleton
当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。注意,Singleton作用域是Spring中的缺省作用域。
要在XML中将bean定义成singleton,可以这样配置:
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
3.1Prototype
Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。
在XML中将bean定义成prototype,可以这样配置:
<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>
或者
<bean id="account" class="com.foo.DefaultAccount" singleton="false"/>
3.1Request
当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例,即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。当处理请求结束,request作用域的bean实例将被销毁。
3.1Session
当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。
4、Bean的自动装配
自动装配是Spring满足bean依赖的一种方式,Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显示地配置
- 在Java中显示地配置
- 隐式地自动装配bean【实现基于Autowired,可以参考这篇文章。使用Autowired甚至可以省略掉set方法 】
5、注解开发
在xml配置文件中增加以下配置
<!-- 开启注解支持-->
<context:annotation-config/>
<!--指定注解扫描包-->
<context:component-scan base-package="com.hpu.entity"/>
5.1注入Bean和属性
@Component
public class User {
@Value("名字")
private String name;
public void setName(String name) {
this.name = name;
}
}
相当于
<bean id="user" class="com.hpu.entity.User">
<property name="name" value="名字"/>
</bean>
注意:如果实体类中没有set方法,xml配置会报红,可以看出Spring默认的注入方式是set注入
5.2衍生的注解
@Component有几个衍生的注解,在web开发中,会按照mvc三层架构进行开发,每一层都有对应的注解:
- dao层:@Repository
- service层:@Service
- controller层:@Controller
这四个注解功能都是一样的,都是代表将某个类注册到spring中,装配Bean
5.3自动装配
就是对@autowired、@resource两个注解的讲解
5.4作用域
使用注解的方式指定Bean的作用域
@Component
@Scope("prototype")
public class User {
@Value("名字")
private String name;
public void setName(String name) {
this.name = name;
}
}
6、JavaConfig实现配置
它通过 Java 类的方式提供 Bean 的定义和配置信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。
新建一个类,使用注解方式注入容器
@Component
public class Cat {
@Value("小橘")
private String name;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}
新建一个配置类
@Configuration
public class BeanConfig {
//通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id
@Bean
public Cat cat(){
return new Cat();
}
}
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
Cat cat = applicationContext.getBean("cat", Cat.class);
System.out.println(cat);
}
}
2、AOP
1、代理模式
为什么学习代理模式,因为AOP的底层机制就是动态代理!
代理模式分为:静态代理、动态代理
1.1静态代理
静态代理角色分析:
- 抽象角色:一般使用接口或者抽象类实现
- 真实角色:被代理的角色
- 代理角色:代理真实角色,一般会做一些附属的操作
- 客户端:使用代理角色来进行一些操作
1、创建一个抽象角色,比如咋们平时做的用户业务,抽象起来就是增删改查!
/**
* @author pss
* @Description: 抽象角色
* @date 2022/1/13 15:07
*/
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
2、我们需要一个真实对象来完成这些增删改查操作
/**
* @author pss
* @Description:
* @date 2022/1/13 15:08
*/
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("查找了一个用户");
}
}
3、需求来了,现在我们需要增加一个日志功能,怎么实现?
思路1 :在实现类上增加代码 【麻烦!】
思路2:使用代理来做,能够不改变原来的业务情况下,实现此功能就是最好的了!
4、设置一个代理类来处理日志!代理角色
/**
* @author pss
* @Description: 抽象角色的代理
* @date 2022/1/13 15:09
*/
public class UserServiceProxy implements UserService {
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
public void log(String msg) {
System.out.println(String.format("调用了%s方法", msg));
}
}
5、测试访问类:
public class Client {
public static void main(String[] args) {
//真实业务
UserServiceImpl userService = new UserServiceImpl();
//代理类
UserServiceProxy proxy = new UserServiceProxy();
//使用代理类实现日志功能!
proxy.setUserService(userService);
proxy.add();
}
}
静态代理的好处:
-
可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
-
公共的业务由代理来完成 . 实现了业务的分工 ,
-
公共业务发生扩展时变得更加集中和方便 .
缺点 :
-
类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 .
-
我们想要静态代理的好处,又不想要静态代理的缺点,所以 , 就有了动态代理 !
1.2动态代理
通过实现InvocationHandler接口,创建一个代理角色,在代理角色中使用set注入抽象角色。代理角色中有两个重要的方法,一个是getProxy(),用来生成代理类,一个是invoke(),用来处理代理实例上的方法调用并返回结果,底层实现是基于反射(method.invoke(target,args)),对抽象角色的增强就是在invoke方法里面实现。
编写一个通用的动态代理实现的类,所有的代理对象设置为Object
/**
* @author pss
* @Description: 通用的动态代理实现类,所有代理对象设置为object即可
* @date 2022/1/13 15:37
*/
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);
}
/**
*
* @param proxy:代理类
* @param method:代理类的调用处理程序的方法对象
* @param args:所需参数
* @return
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
return method.invoke(target,args);
}
// 对代理的类做一些附属操作
public void log(String msg){
System.out.println(String.format("执行了%s方法",msg));
}
}
使用动态代理实现代理前面写的UserService
public class Client {
public static void main(String[] args) {
// 真实对象
UserServiceImpl userService = new UserServiceImpl();
// 代理对象的调用处理程序
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
// 设置要代理的对象
proxyInvocationHandler.setTarget(userService);
// 动态生成代理类
UserService proxy = (UserService) proxyInvocationHandler.getProxy();
proxy.add();
}
}
静态代理有的它都有,静态代理没有的,它也有!
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情
- 公共的业务由代理来完成 . 实现了业务的分工
- 公共业务发生扩展时变得更加集中和方便
- 一个动态代理 , 一般代理某一类业务
- 一个动态代理可以代理多个类,代理的是接口
2、AOP实战
2.1概念
2.2基于xml配置文件
public interface UserService {
void add();
void delete();
void update();
void query();
}
AOP中的【对象】,就是要被增强的类,【对象】中的方法就是 AOP中的【切入点】,就是要被增强的方法
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("add");
}
public void delete() {
System.out.println("delete");
}
public void update() {
System.out.println("update");
}
public void query() {
System.out.println("query");
}
}
AOP中的【切面】,就是增强方法所在的类,切面中的方法就是AOP中的【通知】
public class DiyPoint {
// 前置通知
public void before(){
System.out.println("方法执行前");
}
// 后置通知
public void after(){
System.out.println("方法执行后");
}
}
配置文件
<?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 id="userService" class="com.hpu.aop.UserServiceImpl"/>
<!--切面-->
<bean id="diy" class="com.hpu.aop.DiyPoint"/>
<!--aop的配置-->
<aop:config>
<!--第二种方式:使用AOP的标签实现-->
<aop:aspect ref="diy">
<aop:pointcut id="diyPonitcut" expression="execution(* com.hpu.aop.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before pointcut-ref="diyPonitcut" method="before"/>
<!--通知-->
<aop:after pointcut-ref="diyPonitcut" method="after"/>
</aop:aspect>
</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();
}
}
输出,可以看到【目标对象】中的【切入点】被【切面】中的【通知】增强了
方法执行前
add
方法执行后
2.3基于注解
编写一个【切面】,实现一些【通知】,用于增强【目标对象】中的【切入点】
@Aspect
public class AnnoPointCut {
@Before("execution(* com.hpu.aop.UserServiceImpl.*(..))")
public void before(){
System.out.println("注解前置增强");
}
@After("execution(* com.hpu.aop.UserServiceImpl.*(..))")
public void after(){
System.out.println("注解后置增强");
}
}
配置文件
<?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 id="userService" class="com.hpu.aop.UserServiceImpl"/>
<bean id="annotationPointcut" class="com.hpu.aop.AnnoPointCut"/>
<aop:aspectj-autoproxy/>
</beans>