Spring中你可能不知道的事(一)

Spring做为Java的王牌开源项目,相信你们都用过,可是可能你们仅仅用到了Spring最经常使用的功能,Spring实在是庞大了,不少功能可能一生都不会用到,今天我就罗列下Spring中你可能不知道的事。一是能够帮助你们之后阅读源码,知道Spring为何会这么写,二是能够做为知识储备,当人家不会的时候,你正好知道这个点,三下五除二就搞定了,嘿嘿。三是平时吹牛的时候能够更有资本。。。固然最重要的就是能够对Spring有一个更全面的认识。程序员

register

如今官方推荐应该就是用JavaConfig的风格来完成Spring的配置,也是如今的主流用法。咱们常常这么写:数组

@Configuration
@ComponentScan
public class AppConfig {
}
复制代码
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);
复制代码

这段代码太简单,就再也不解释了,可是咱们能够把方法拆分下:bash

AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
复制代码

在第二行代码才去注册配置类。app

效果是同样的,咱们除了能够注册配置类,还能够单独注册一个 bean:ide

@Component
public class Service {
}
复制代码
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(Service.class);
        context.refresh();//很重要        
        System.out.println(context.getBean(Service.class).getClass().getSimpleName());
    }
}
复制代码

这样咱们就能够完成对bean的注入,这里面有一个细节很重要,须要调用refresh方法,否则会报错:函数

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(Service.class);
        System.out.println(context.getBean(Service.class).getClass().getSimpleName());
    }
}
复制代码

image.png

registerBean

上面的方法虽然能够单独注册一个bean,可是在bean的类上,你必须打上@Component或者@Service或者@Repository,若是你不想用默认的做用域,也得打上@Scope,有没有一种方法,能够不用在bean的类上打各类注解?此时registerBean出场了:post

public class Service {
    public Service(String str){
        System.out.println(str);
    }
}
复制代码
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.registerBean("myService", Service.class, () -> new Service("Hello"), z -> {
            z.setScope("prototype");
        });
        context.refresh();
        System.out.println(context.getBean("myService").getClass().getSimpleName());
        System.out.println(context.getBeanDefinition("myService").getScope());
    }
}
复制代码

我注册了名为myService的Bean,类是Service,而且做用域为prototype,且会调用带参的构造方法:测试

image.png

BeanPostProcessor

若是说上面两个小点不重要,那么这一个就是重磅级的了,BeanPostProcessor是Spring扩展点之一,BeanPostProcessor是一个接口,程序员能够经过实现它,插手bean的实例化过程,在bean建立先后作一些事情。在Spring内部,也大量的运用了BeanPostProcessor来完成各类功能。咱们能够看下Spring内部有多少类实现了BeanPostProcessor接口(注意,注意,前方高能)。ui

image.png

Spring内部有这么多类(间接)实现了BeanPostProcessor接口,可想而知这个接口的重要性,那么这个接口应该怎么使用呢,很简单,咱们只须要写一个类去实现BeanPostProcessor接口就能够。this

在这里,我利用这个接口,来完成一个阉割版的JDK动态代理的注入:

首先定义一个接口:

public interface Service {
    void query();
}
复制代码

实现类:

@Component
public class ServiceImpl implements  Service {
    @Override
    public void query() {
        System.out.println("正在查询中");
    }
}
复制代码

实现InvocationHandler接口:

public class MyInvationHandler implements InvocationHandler {
    private Object target;

    public MyInvationHandler(Object target){
        this.target=target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("进来了");
        Object obj = method.invoke(target, args);
        System.out.println("出去了");
        return obj;
    }
}
复制代码

实现BeanPostProcessor 接口:

@Component
public class MyBeanPostProcess implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Object o = Proxy.newProxyInstance(MyBeanPostProcess.class.getClassLoader(),
                bean.getClass().getInterfaces(), new MyInvationHandler(bean));
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
复制代码

配置类

@Configuration
@ComponentScan
public class AppConfig {
}
复制代码

测试方法:

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean(Service.class).query();
    }
}
复制代码

运行结果:

image.png

有木有很神奇,无论在main方法,仍是业务的实现类,都没有看到JDK动态代理的影子,可是动态代理真真实实生效了,这就是BeanPostProcessor接口的神奇所在,事实上,Spring内部也是经过实现BeanPostProcessor接口来完成动态代理的,这个暂时不表。

BeanFactoryPostProcessor

BeanFactoryPostProcessor也是Spring的扩展点,程序员能够经过实现它,读取bean的定义,而后对其进行修改,好比我须要修改bean的做用域为prototype,能够这么作:

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
        factory.getBeanDefinition("repo").setScope("prototype");
    }
}
复制代码
@Repository
public class Repo {
}
复制代码
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        System.out.println(context.getBeanDefinition("repo").getScope());
    }
}
复制代码

image.png
你们都知道bean的默认做用域为singleton,这里就经过实现BeanFactoryPostProcessor接口,把做用域改为了prototype。

BeanFactoryPostProcessor 在 BeanPostProcessor以前。

单例bean中有原型bean

若是一个单例的bean中,包含原型的bean,会发生什么事情呢?咱们写一个例子看一下:

@Configuration
@ComponentScan
public class AppConfig {
    @Bean
    @Scope("singleton")
    public Single singleton(){
        return new Single();
    }
    @Bean
    @Scope("prototype")
    public Prototype prototype(){
        return new Prototype();
    }
}
复制代码
public class Single {
    public Single(){
        System.out.println("Single构造方法");
    }
    @Autowired
    private Prototype prototype;
    public Prototype getPrototype() {
        return prototype;
    }
    public void setPrototype(Prototype prototype) {
        this.prototype = prototype;
    }
    public void say() {
        System.out.println(this);
        prototype.say();
    }
}
复制代码
public class Prototype {
    public Prototype(){
        System.out.println("Prototype构造方法");
    }
    public void say() {
        System.out.println(this);
    }
}
复制代码
@Component
public class Test {
    @Autowired
    Single single;
    public void run() {
        for (int i = 0; i < 5; i++) {
            single.say();
        }
    }
}
复制代码

由于代码比较长,避免你们上下来回滚动,我简单的说明下这段代码:Single类是单例的,Prototype是原型的,Single类依赖Prototype,分别给两个类添加一个构造方法,打印一句话,Single类中的方法调用Prototype类的方法,两个方法都打印this。而后再测试方法中自动注入Single,循环5次,调用Single类中的方法。

运行结果:

image.png

这结果明显有问题,Single由于是单例的,只能执行到一次构造方法,每次打印出来的对象也相同,这是没有问题的,可是Prototype是原型的,也只运行了一次构造函数,打印出来的对象也相同,这就有问题了。

这问题怎么解决呢?

ApplicationContextAware

对Single类进行改造,让它实现ApplicationContextAware接口中的setApplicationContext方法:

public class Single implements ApplicationContextAware {
    public Single() {
        System.out.println("Single构造方法");
    }

    private ApplicationContext context;

    public void say() {
        System.out.println(this);
        context.getBean(Prototype.class).say();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
复制代码

运行结果:

image.png

说的简单点,就是经过ApplicationContextAware接口中的setApplicationContext方法,得到ApplicationContext ,赋值给类中的变量ApplicationContext context, 而后从context中得到Prototype Bean。

此方法须要依赖ApplicationContext。

lookup

@Component
@Scope("singleton")
public class Single {
    public Single() {
        System.out.println("Single构造方法");
    }
    public void say() {
        System.out.println(this);
        getPrototype().say();
    }
    @Lookup
    public Prototype getPrototype() {
        return null;
    }
}
复制代码
@Component
@Scope("prototype")
public class Prototype {
    public Prototype(){
        System.out.println("Prototype构造方法");
    }

    public void say() {
        System.out.println(this);
    }
}
复制代码

运行结果:

image.png

此方法须要把配置类中的定义bean改成在类上加注解的方式。

Import

Import是Spring提供的注解,能够经过这个注解,在一个类引入另一个类, 而且自动完成另一个类的注册:

@Configuration
@Import(ServiceImpl.class)
public class AppConfig {
}
复制代码
public class ServiceImpl  {
    public void query() {
        System.out.println("正在查询中");
    }
}
复制代码
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean(ServiceImpl.class).query();
    }
}
复制代码

运行结果:

image.png

能够看到虽然ServiceImpl类上没有打上任何注解,可是在AppConfig配置类上经过Import注解,把ServiceImpl给引入进来了,而且自动注册了ServiceImpl。

也许,单单使用Import注解,会把代码搞得更复杂,因此须要搭配使用,才能把它的能力发挥出来,下面让咱们有请ImportSelector。

ImportSelector

让咱们把目光回到介绍BeanPostProcessor的这一段中,在其中,咱们定义了一个MyBeanPostProcess来完成JDK动态代理,可是让咱们想一个问题,若是咱们不须要使用这个MyBeanPostProcess了,怎么办?咱们须要把MyBeanPostProcess类上的Component注解删除,哪天又须要使用了,还得加上,若是只有一个类,还不算糟糕,可是如何有几十个类呢?至关麻烦,咱们能不能在一个类中统一处理,须要启动哪些Bean就像Spring Boot 同样?固然能够。咱们能够借助于ImportSelector来完成:

首先咱们须要定义一个类,实现ImportSelector 中的 selectImports方法,这个方法返回的是须要与此类绑定的bean的名称的数组:

public class AspectSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{MyBeanPostProcess.class.getName()};
    }
}
复制代码

咱们再自定义一个注解,打上Import注解,引入上面的类:

@Import(AspectSelector.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableAspect{
}
复制代码

注意看AppConfig 的注解,多了一个EnableAspect注解:

@Configuration
@ComponentScan
@EnableAspect
public class AppConfig {
}
复制代码
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean(Service.class).query();
    }
}
复制代码

而后咱们把MyBeanPostProcess上的注解删除,运行:

image.png

当咱们不须要使用MyBeanPostProcess了,只要在AppConfig删除EnableAspect注解就OK了。

这是至关炫酷的一个技巧,在SpringBoot大量使用,好比开启事务管理EnableTransactionManagement。

FactoryBean

FactoryBean常常会和BeanFactory放在一块儿比较,由于他们太像了,不过仅仅是长得像,其实它们彻底不是同一个东西。

FactoryBean,是一种特殊的Bean,特殊在它除了自身是Baen,还能够生产Bean,是否是很符合FactoryBean这个名称?

FactoryBean是一个接口,咱们须要实现它:

@Component
public class MyFactoryBean implements FactoryBean {

    public Object getObject() throws Exception {
        return new DataSource();
    }
    @Override
    public Class<?> getObjectType() {
        return null;
    }
}
复制代码
public class DataSource {
}
复制代码
@Configuration
@ComponentScan
public class AppConfig {
}
复制代码
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        System.out.println(context.getBean("myFactoryBean").getClass().getSimpleName());
        System.out.println(context.getBean("&myFactoryBean").getClass().getSimpleName());
    }
}
复制代码

运行结果:

image.png

咱们能够看到MyFactoryBean上打了一个Component,它能够被扫描到,可是DataSource上什么都没有加,按理来讲,是没有被扫描到的,可是它就是被注册进去了,由于它实现了FactoryBean接口,在getObject方法返回了DataSource的实例,能够理解为DataSource是MyFactoryBean生产出来的一个Bean。

让咱们仔细看下main方法和运行结果,能够看到 MyFactoryBean自己的BeanName是&myFactoryBean,MyFactoryBean生产出来的Bean的BeanName是myFactoryBean。

这有什么用呢?能够隐藏构建Bean的细节。若是咱们的DataSource是第三方提供的,里面有一堆的字段须要配置,还有一堆的依赖,若是咱们来配置的话,根本没法完成,最好的办法就是仍是交给维护第三方去配置,可是DataSource是不能去修改的。这个时候,就能够用FactoryBean来完成,在getObject配置好DataSource,而且返回。咱们常用的Mybatis也利用了FactoryBean接口。

Spring实在是太庞大了,不少功能都不是常常用,我在这里只是稍微罗列了几个小点,加上咱们常常用的那些,可能还不及Spring的十分之一,这已是乐观的了。

限于篇幅关系,这一章的内容到这里就结束了,其中BeanPostProcessor,BeanFactoryPostProcessor,FactoryBean,Import,ImportSelector这几块内容很是重要,正在因为这些,才让Spring变的更加灵活,更加好用。

相关文章
相关标签/搜索