Spring family bucket - the knowledge you need to know

  • InitializingBean Interface
    package org.springframework.beans.factory;
    public interface InitializingBean {
    	void afterPropertiesSet() throws Exception;
    }
    This interface method on this one, this interface in some middleware will certainly be involved, because of its unique charm, first of all look at its location bean instance of execution:

    when the general need to use this interface to achieve it? When you need to set the value of the bean property, it is not feeling equal to not say anything? Put it this way: write code when you can use this method to trigger a number of tasks, such as polling the database to obtain data; initialization parameters; triggering a number of cyclical events. In particular, the need to obtain the same configuration items from the database when a project, you can use this method only when the characteristics of Java Bean started the call, reducing the amount of access to the database.


     
  • Aware interfaces
    such as the most used: ApplicationContextAware, BeanFactoryAware, XXXAware ......
    when the general need to use this interface to achieve it? When you want to hold XXX bean as an attribute, you realize XXXAware, for example, you want to define a ApplicationContext Bean object, you need to initialize it, then you can achieve ApplicationContextAware, Bean in Spring container loading process, the will call: the following example, a method to achieve setApplicationContext ApplicationContextAware interface, Spring container will invoke the appropriate setApplicationContext suitable method, reference will be transmitted to the ApplicationContext applicationContext ApplicationContextHolder the properties defined below. When XXXAware trigger to enforce it, "referring to the above chart, right, left chart: Aware detects and related interfaces .......
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    public class ApplicationContextHolder implements ApplicationContextAware {
    	private static ApplicationContext applicationContext;
    	@Override
    	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    		ApplicationContextHolder.applicationContext = applicationContext;
    	}
    	public static ApplicationContext getApplicationContext() {
    		return applicationContext;
    	}
    }


     

  • FactoryBean Interface
    package org.springframework.beans.factory;
    import org.springframework.lang.Nullable;
    public interface FactoryBean<T> {
    	@Nullable
    	T getObject() throws Exception;
    
    	@Nullable
    	Class<?> getObjectType();
    
    	default boolean isSingleton() {
    		return true;
    	}
    }
    General When do we need to implement this interface it? FactoryBean core interface is that you can get through a getObject method is that it produces objects, so we create more convenient when Proxy proxy object. Some bean, if configured by the way, will become more cumbersome and complex, this time using the appropriate encoding in some cases was quite good Spring bean container loaded by default is a single example, if you want your writing a bean is not a single embodiment, except that the outer profile settings, are now popular method isSingleton implement this interface, returns false. This interface, due to limited capacity, not feeling their best to the readers self-YY.

     
  • SmartLifecycle Interface
    public interface SmartLifecycle extends Lifecycle, Phased {
    	int DEFAULT_PHASE = Integer.MAX_VALUE;
    	default boolean isAutoStartup() {
    		return true;
    	}
    	default void stop(Runnable callback) {
    		stop();
    		callback.run();
    	}
    	@Override
    	default int getPhase() {
    		return DEFAULT_PHASE;
    	}
    }
    
    public interface Lifecycle {
    	void start();
    	void stop();
    	boolean isRunning();
    }
    
    public interface Phased {
    	//Return the phase value of this object.
    	int getPhase();
    }
    General When do we need to implement this interface it? The bloggers say more: if the business needs to do some action when the spring container startup and shutdown, such as starting the server netty and elegant turn off the server. As can be seen from a to accept the above mentioned, the perception of change in the final container from the Lifecycle, and SmartLifecycle Lifecycle enhanced version only, can be customized priority (getPhase), to decide whether to start with the container (isAutoStartup), and stops runnable objects (STOP (the runnable)) https://blog.csdn.net/boling_cavalry/article/details/82051356



     
  • ApplicationListener, ApplicationEventPublisher interfaces
    can listen to an event event, listen for the event type is the interface E, when it was time to publish event types E, and listens to achieve a ApplicationListener type of class E is triggered onApplicationEvent method. Spring has a lot of built-in internal events, see the source code can feel.
    package org.springframework.context;
    import java.util.EventListener;
    public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    	void onApplicationEvent(E event);
    }
    
    public interface ApplicationEventPublisher {
    	void publishEvent(ApplicationEvent event);
    	void publishEvent(Object event);
    }
    This interface is also extremely wide application, when you want to take place in certain operations, trigger certain actions, you can use this interface. For example, our programmer, when you know your family fortune, there are 10 million, you definitely want to know first and immediately resigned ~
    //定义一个事件类型
    import org.springframework.context.ApplicationEvent;
    public class MoneyGetEvent extends ApplicationEvent {
        public MoneyGetEvent(Object source) {
            super(source);
        }
    }
    
    //发布事件
    import org.springframework.context.ApplicationEventPublisher;
    import org.springframework.context.ApplicationEventPublisherAware;
    public class PublishEventClass  implements ApplicationEventPublisherAware {
        private ApplicationEventPublisher eventPublisher;
        /**
         * 实现了ApplicationEventPublisherAware接口,容器加载该bean的时候会调用此setApplicationEventPublisher方法,
         * 给该bean的eventPublisher属性赋值,此对象用来发布事件,发布后,会触发对此事件类型感兴趣的bean的
         */
        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
            this.eventPublisher = eventPublisher;
        }
        //当调用该方法的时候,会触发MoneyGetEventListener的onApplicationEvent方法
        public void moneyGet() {
           eventPublisher.publishEvent(new MoneyGetEvent("儿子,家里拆迁分了10个亿,还是美元"));
        }
    }
    
    //监听事件
    import org.springframework.context.ApplicationListener;
    import org.springframework.stereotype.Component;
    @Component
    public class MoneyGetEventListener implements ApplicationListener<MoneyGetEvent> {
        @Override
        public void onApplicationEvent(MoneyGetEvent event) {
            System.out.println("老板,我摊牌了,我是亿万富翁,上你个屁班!");
        }
    }
  • Custom Spring Boot Start  
     

    spring-boot-starter: spring-boot configuration can be omitted many tedious, it can be said that many starter contributed. E.g. Redis integrated spring-boot, only introduced pom.xml spring-boot-starter-data-redis, spring.redis.database configuration items and several key profile is added, as well as conventional starter spring- boot-starter-web, spring-boot-starter-test, spring-boot-starter-jdbc, compared to traditional xml configuration can be said to greatly reduce the integration effort. Find starter jar package resources / META-INF / spring.factories startup file SpringBoot, according spring.factories configuration file, find the class to be automatically configured, for example, read:

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.test.springboot.starter.helloworld.configuration.MyAutoConfiguration 

    Specified Configuration, is automatically created in accordance with Conditional bean conditions on Configuration, into the container (spring.factories is not essential, it may be in the startup class add the following comments on the automatic configuration: @ImportAutoConfiguration ({MyAutoConfiguration.class}))
    exciting example : https://blog.csdn.net/boling_cavalry/article/details/82956512
    common comment:

    @ConditionalOnBean:当容器中有指定的Bean的条件下
    @ConditionalOnClass:当类路径下有指定的类的条件下
    @ConditionalOnExpression:基于SpEL表达式作为判断条件
    @ConditionalOnJava:基于JVM版本作为判断条件
    @ConditionalOnJndi:在JNDI存在的条件下查找指定的位置
    @ConditionalOnMissingBean:当容器中没有指定Bean的情况下
    @ConditionalOnMissingClass:当类路径下没有指定的类的条件下
    @ConditionalOnNotWebApplication:当前项目不是Web项目的条件下
    @ConditionalOnProperty:指定的属性是否有指定的值
    @ConditionalOnResource:类路径下是否有指定的资源
    @ConditionalOnSingleCandidate:当指定的Bean在容器中只有一个,或者在有多个Bean的情况下,用来指定首选的Bean
    @ConditionalOnWebApplication:当前项目是Web项目的条件下

     
  • Spring's transaction manager
  • ApplicationContextInitializer


    TODO......

 

 

Published 142 original articles · won praise 345 · Views 450,000 +

Guess you like

Origin blog.csdn.net/zhengchao1991/article/details/99608768