Spring小记

用maven项目导入spring依赖

Spring的特点:

在这一节中,将会尽量使用Spring的原生方式,即xml配置

非侵入的:

项目的代码不需要感知到spring的存在,不用使用spring的api。Spring的作用更多的是将各个解耦的代码模块连接起来,即胶水的作用。

Ioc容器:

Inversion of control,控制反转,即一个对象不需要知道他所装配的实例的创建和配置过程,而只要使用set方法来注入这个实例。

	class Server{
		// 业务层来初始化实例
		Hello hello = new Hello("HelloConfig.xml");
	}
	class ServerIoc{
		Hello hello;
		// 业务层不初始化实例,而是装配
		void setHello(Hello hello) {
			this.hello = hello;
		}
	}

既然当前层并不初始化实例,这些实例就应该在另一处被初始化,Spring就负责管理这些实例的初始化和生命周期,因此Spring叫做Ioc容器,所以我们需要告知Spring应该怎么初始化这些实例,就需要xml文件和引用ClassPathXmlApplicationContext来获取相应的上下文来进行这些实例的配置。这也叫类在Spring中的注册,从而Spring能够感知到这些类,因此Spring对任何类的使用都应当首先注册这个类。

<?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:util="http://www.springframework.org/schema/util"
       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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="user" class="dao.User">
        <property name="name" value="gzb"/>
    </bean>
    <bean id="server" class="server.Server">
        <property name="user" ref="user"></property>
    </bean>
</beans>

通过1,2点的结合,spring提供了一种思想,将实例的使用和初始化过程隔离在不同的阶段中,从而实现代码的解耦(虽然随着注解开发的普及,到SpringBoot的出现,装配已经越来越多的被内置到注解上去了,但这种思想仍然是解耦友好的)
3.AOP:
面向切面的,1,2点提供了一种代码的解耦角度,这种解耦是层次的纵向解耦,也就是 持久层,业务层,和表现层的分离。而AOP关注的是层次的横向关注点,比如可能在业务层,我们关注一些类似于日志,或者是debug信息等拓展出来的功能。
通过定义切面和切入点来产生动态代理的效果,动态代理的效果和java中的Proxy类和InvokeHandler类的效果类似。在这两个类中,通过反射的技术来获取类名,方法名等代理对象所需要知道的信息,并做出一定的处理,比如日志功能
一个经典的Proxy和InvokeHandler的协作如下,需要特别注意,App类中的Proxy类使用了接口类型,因为动态代理代理的是接口

public interface GetName {
    void getName();
}

public class App 
{
    public static void main( String[] args )
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
        Server server = (Server)context.getBean("server");
        ProxyHandler proxyHandler = new ProxyHandler(server);
        GetName proxy = (GetName) Proxy.newProxyInstance(Server.class.getClassLoader(), Server.class.getInterfaces(), proxyHandler);
        proxy.getName();
    }
}

public class User {
    String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

public class Server implements GetName{
    User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public void getName() {
        System.out.println(user.getName());
    }
}

public class ProxyHandler implements InvocationHandler {
    Object object;

    public ProxyHandler(Object object) {
        this.object = object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("在调用"+method.getName()+"方法前");
        method.invoke(object, args);
        System.out.println("在调用"+method.getName()+"方法后");
        return null;
    }
}

上面的代码只是用spring注册了一个实例,动态代理的过程完全由java原生api实现。Proxy类代理的是接口(代理什么),而将代理的工作完全交给InvocationHandler来做(怎么代理),因此动态代理完全就是一个死代码,我们只要专心的在handler中编写代理的细节即可,在invoke方法中,能够获取到的是Method类,因此还需要传递一个实例进去来调用方法。
Spring的AOP和这个类似,只是Spring提供了一些api来提供一些更加精细的控制,比如切面的范围,Proxy一次只能代理一个类,而Spring可以任意的配置,一次性代理某个包下的某些类的某些方法。
仍然让User,Service类保持不变

public class SpringProxy implements MethodBeforeAdvice, AfterReturningAdvice {

    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("在调用"+method.getName()+"前");
    }

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("在调用"+method.getName()+"后");
    }
}
public class App 
{
    public static void main( String[] args )
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
        GetName server = (GetName)context.getBean("server");
        server.getName();
//        ProxyHandler proxyHandler = new ProxyHandler(server);
//        GetName proxy = (GetName) Proxy.newProxyInstance(Server.class.getClassLoader(), Server.class.getInterfaces(), proxyHandler);
//        proxy.getName();
    }
}

加入spring原生的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:util="http://www.springframework.org/schema/util"
       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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="user" class="dao.User">
        <property name="name" value="gzb"/>
    </bean>
    <bean id="server" class="server.Server">
        <property name="user" ref="user"></property>
    </bean>
    <bean id="springProxy" class="server.SpringProxy"/>
    <aop:config>
<!--        切入点-->
        <aop:pointcut id="pointcut" expression="execution(* server.Server.*(..))"/>
<!--        切入方式,用哪个类切入,切入在哪-->
        <aop:advisor advice-ref="springProxy" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

使用spring的时候要注意maven正确引入dependencies
感觉上是比我们自己写动态代理要麻烦一点,但是我们注意到,SpringProxy类中只要声明相应的接口就可以专注在代码的实现上。而在xml中进行切入点的配置。用动态代理的方式对比来说,就是InvocationHandler被AOP接口类取代了,而Proxy类被xml配置取代了,Proxy类一次只能代理一个类的接口,xml可以在execution中方便的拓展代理的类和方法,这又是Spring的将代码和装配方式解耦方式的体现。

Spring的不同的装配方式

AOP的注册形式

上文介绍了通过Spring api的方式来注册,但是有点过于反人类了,接口,xml配置里面有一个想不起就比较麻烦

通过aop:aspect方式来配置切面

public class Aspect {
    void proxyBefore() {
        System.out.println("before");
    }
    void proxyAfter() {
        System.out.println("after");
    }
}

	<aop:config>
        <aop:aspect id="aopAspect" ref="aspect">
            <aop:pointcut id="pointcut" expression="execution(* server.Server.*(..))"/>
            <aop:before method="proxyBefore" pointcut-ref="pointcut"/>
            <aop:after method="proxyAfter" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

这个方法是好写一点,但是只能写普通的函数,因此效果很弱

这个方法也有注解版本

@org.aspectj.lang.annotation.Aspect
public class Aspect {
    @Before("execution(* server.Server.*(..))")
    void proxyBefore() {
        System.out.println("before");
    }
    @After("execution(* server.Server.*(..))")
    void proxyAfter() {
        System.out.println("after");
    }
}

注意要在xml中加入,这样只要注册完bean就可以直接使用了

    <aop:aspectj-autoproxy/>

突然感觉原生的api还挺友好的…因为这两个东西好像是没什么用

bean的配置方式

xml配置

上文已经写了

注解配置

通过java注解来进行bean的装配,只能装配比较简单的情况,比如装配array,list,set等等就不能使用注解装配
在xml中指定注解生效,和扫描注解的包

<context:annotation-config/>
<context:component-scan base-package="dao"/>
<context:component-scan base-package="server"/>

使用注解配置,@Component就相当于是

<bean id="类的小写" class="这个类">
@Component
public class User {
    String name;
    public String getName() {
        return name;
    }
    @Value("gzb")
    public void setName(String name) {
        this.name = name;
    }
}
@Component
public class Server implements GetName {
    User user;
    @Autowired
    public void setUser(User user) {
        this.user = user;
    }
    public void getName() {
        System.out.println(user.getName());
    }
}

一些常用的注解
类注解:@Component,@Scope
字段和属性注解:@Autowire,@Quialifier,@Value

javaConfig类

不使用xml而是使用完全的java来进行配置,首先使用JavaConfig的上下文

**public static void main( String[] args )
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        GetName server = (GetName) context.getBean("server");
        server.getName();
    }

在config中注册bean,在bean类中用注解进行装配

package server;

import dao.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import server.Server;

@Configuration
public class Config {
    @Bean
    public User user() {
        return new User();
    }
    @Bean
    public Server server() {
        return new Server();
    }
}

c和p命名空间注入

这个了解一下即可,感觉是不如用注解和xml结合的方式来注入

小结

几个注意的点,

Ioc容器
xml配置方法,xml注解配置方法,纯java注解方法
AOP
Spring原生api(功能强),自定义类切面,自定义类切面的注解版本(有点没用)
声明式事务
后面再更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值