cool hit counter A schematic summary of Spring_Intefrankly

A schematic summary of Spring


I. The life course of a bean

Bean's life process can be borrowed from Servlet's life process, and understanding its life process is useful for both thinking and later use.

Beans can be loaded in two ways, using a BeanFactory and an applicationContext, and the following summarizes the bean declaration cycle for these two ways.

applicationContext:

(a) To start with a kind of life-cycle flow chart to summarize.

1: Bean creation.

The container looks for the definition information of the bean and instantiates it, i.e. new an object,.

2: Attribute injection.

usedependency injection,Spring in accordance withBean Defining Information ConfigurationBean All Properties, equivalent to callingset method for the propertyset operations

3. If this bean implements the BeanNameAware interface, it will call the setBeanName(String beanId) method that it implements, where the ID of the bean in the Spring configuration file is passed

4. If thisBean AchievedBeanFactoryAware interface, will call its implementation of thesetBeanFactory(), The message isSpring The factory itself( You can use this method to get otherBean)

5. If thisBean AchievedApplicationContextAware interface, will callsetApplicationContext(ApplicationContext) approach, transmitted inwardsSpring context, This approach also allows for the steps4, but better than4 better, thinkApplicationContext beBeanFactory son of interface, There are more ways to implement

6. If thisBean It's linked.BeanPostProcessor interface, will call thepostProcessBeforeInitialization(Object obj, String s) approach,BeanPostProcessor Often used as isBean Change of content, And since this is inBean Called at the end of initializationAfter approach, Can also be used for memory or caching techniques

7. If the setting isinitializingBean interface, will then call the implementedafterPropertiesSet() approach;

8. If the bean has an init-method property configured in the Spring configuration file it will automatically call its configured initialization method [equivalent to a custom method]

9. If this bean is associated with the BeanPostProcessor interface, the postAfterInitialization(Object obj, String s) method will be called

Caution. Once the above is done, the bean is ready to be used , that the bean is a single, so generally we call the bean with the same ID will be in the instance with the same content address

10. The container shuts down, and when the bean is no longer needed, it goes through a cleanup phase. If the bean implements the DisposableBean interface, it will call the destroy method of its implementation, and if the destroy-method property is configured in the Spring configuration of this bean, it will automatically call its configured destroy method

BeanFactory:

the following analysis of the life cycle process of the BeanFactory, which is relatively simplified in comparison to the ApplicationContext.

The following diagram provides a summary.

The following is an example of a BeanFactory to illustrate the life cycle activities of a bean

  • Bean creation, where the BeanFactory reads the bean definition file and generates individual instances
  • Setter injection, which performs property dependency injection of beans
  • BeanNameAware's setBeanName(), or its setBeanName method if it implements this interface
  • BeanFactoryAware's setBeanFactory(), if it implements the interface, executes its setBeanFactory method
  • InitializingBean's afterPropertiesSet(), or if the interface is implemented, its afterPropertiesSet() method is executed
  • Define init-method in the bean definition file
  • DisposableBean ofdestroy(), When the container is closed, in caseBean class implements the interface, then execute itsdestroy() approach
  • Bean Defined in the definition filedestroy-method, When the container is closed, It can be found onBean In the definition file use“destory-method” Method of definition

in case useApplicationContext to maintain aBean life cycle of the, Then it's basically the same process as above, Only in the executionBeanNameAware ofsetBeanName() back, if notBean class implements theorg.springframework.context.ApplicationContextAware interface, then implement itssetApplicationContext() approach, and then proceed toBeanPostProcessors ofprocessBeforeInitialization() In fact, ApplicationContext, in addition to maintaining containers like BeanFactory, also provides a richer framework of features such as bean messaging, event handling mechanisms, etc.

Presentation of results.

II.BeanFactory interface harmonyApplicationContext interface What's the difference? ?

①ApplicationContext interface succeedBeanFactory interface,Spring The core plant isBeanFactory ,BeanFactory Take delayed loading, first timegetBean is initialized only when theBean, ApplicationContext is initialized when the configuration file is loadedBean。

②ApplicationContext is an extension to BeanFactory, which allows internationalization, event passing and bean auto-assembly as well as various application layer Context implementations

The development is basically in useApplicationContext, web sports event useWebApplicationContext, Rarely usedBeanFactory

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
IHelloService helloService = (IHelloService) beanFactory.getBean("helloService");
helloService.sayHello();

III. How the bean is loaded.

1) Instantiated using class constructor (no parameters by default)

 <bean id="bean1" class="cn.itcast.spring.b_instance.Bean1"></bean>

2) use Static factory method instantiation( simple factory model)

 // The meaning of the following configuration: call the getBean2 method of the Bean2Factory to get bean2
<bean id="bean2" class="cn.itcast.spring.b_instance.Bean2Factory" factory-method="getBean2"></bean>

3) use Instance factory method instantiation( factory method model)

 // Create the factory instance bean3Facory first, then create the target bean instance from the factory instance
<bean id="bean3Factory" class="cn.itcast.spring.b_instance.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>

IV. Please introduce the life cycle and scope of beans in Spring Framework

(1) bean definition

Inside the configuration file with<bean></bean> to define。

(2) bean initialization

There are two ways to initialize :

A.This is done in the configuration file by specifying the init-method attribute

B.Implement the org.springframwork.beans.factory.InitializingBean interface

(3) bean call

There are three ways to get the bean instance and make the call

(4) bean destruction

There are two ways to destroy

A.Use the destroy-method attribute specified in the configuration file

B. realizeorg.springframwork.bean.factory.DisposeableBean interface

##Scope

singleton

When abean with a scope ofsingleton, or soSpring IoC There will only be one sharedbean an actual example, And all of the pairs ofbean requests, provided thatid associated with thatbean Matching definitions, will only returnbean of the same instance。

prototype

Prototype scopebean would result in a change in the value of thebean requesting( Inject it into anotherbean in, Or programmatically call the container'sgetBean() approach) are created when a newbean an actual example。 based on experience, For all statefulbean probably useprototype scope of an action, And for the statelessbean should usesingleton scope of an action

request

in one goHTTP Request in progress, anbean The definition corresponds to an instance; i.e. every timeHTTP The requests will have their ownbean an actual example, They are based on a certainbean Created by definition。 that role The domain is only available on the basis ofweb ofSpring ApplicationContext Situations valid。

session

In aHTTP Session in, anbean The definition corresponds to an instance。 This scope is only available in theweb ofSpringApplicationContext Situations valid。

global session

In a globalHTTP Session in, anbean The definition corresponds to an instance。 typical situation, only in useportletcontext valid at the time of。 This scope is only available in theweb ofSpring ApplicationContext Situations valid。

V. How many ways are there to inject properties into a bean?

spring supports constructor injection and setter method injection

Constructor injection, via the<constructor-arg> Element completion injection

The setter method is injected, via the<property> Element completion injection【 Common approaches in development】

Six, what are the core classes of Spring and what is the role of each?

BeanFactory: produces a new instance that can implement the singleton pattern

BeanWrapper: provides unified get and set methods

ApplicationContext: provides the implementation of the framework, including all the functions of the BeanFactory

Seven, how to configure the database driver inside Spring?

Use "

com.mchange.v2.c3p0.ComboPooledDataSource

"Data source to configure the database driver. Examples are as follows.

      <!--  Configuring the database data source -->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">      
        <property name="driverClass" value="${jdbc.driverClassName}"/>      
        <property name="jdbcUrl" value="${jdbc.url}"/>      
        <property name="user" value="${jdbc.username}"/>      
        <property name="password" value="${jdbc.password}"/>
               
        <!--  Initialize connection size -->
        <property name="initialPoolSize" value="${initialSize}"/>
        <!--  Minimum number of connection pools -->
        <property name="minPoolSize" value="${minActive}" />
        <!--  Maximum number of connection pools -->
        <property name="maxPoolSize" value="${maxActive}"/>
         <property name="autoCommitOnClose" value="true"/>
    </bean> 

Eight, Spring inside the applicationContext.xml file can not be changed to other file names?

ContextLoaderListener It's aServletContextListener, It's in yourweb Initialized at application startup。 By default, It will be inWEB-INF/applicationContext.xml Document searchSpring configuration。

You can define a<context-param> The element name is”contextConfigLocation” to change the location of the Spring configuration file. Examples are as follows.

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener
        <context-param> 
         <param-name>contextConfigLocation</param-name> 
         <param-value>/WEB-INF/xyz.xml</param-value> 
        </context-param>   
    </listener-class> 
</listener> 

IX. How does Spring handle thread concurrency?

Spring uses ThreadLocal to solve thread safety problems [blog has a section dedicated to the analysis of TreadLocal]

We know that in general, only stateless beans can be shared in a multi-threaded environment, and in Spring, the vast majority of beans can be declared as singleton scopes. It is because Spring uses ThreadLocal for non-thread-safe state for some beans (such as RequestContextHolder, TransactionSynchronizationManager, LocaleContextHolder, etc.) to make them thread-safe as well, because stateful beans can then be shared in multiple threads.

Both ThreadLocal and thread synchronization mechanisms are designed to solve the problem of conflicting access to the same variables in multiple threads.

In the synchronization mechanism, only one thread is guaranteed to access the variable at the same time through the locking mechanism of the object. This is when the variable is shared by multiple threads, and using the synchronization mechanism requires the program to carefully analyze when to read or write to the variable, when to lock an object, when to release the object lock, and other tedious issues, making the program relatively difficult to design and write.

ThreadLocal, on the other hand, addresses concurrent access to multiple threads from a different perspective. ThreadLocal provides a separate copy of the variable for each thread, thus isolating multiple threads from conflicting access to data. Since each thread has its own copy of the variable, there is thus no need to synchronize that variable. ThreadLocal provides thread-safe shared objects that can encapsulate unsafe variables into ThreadLocal when writing multi-threaded code.

Since any type of object can be held in ThreadLocal, the get() provided by lower versions of the JDK returns an Object object, which requires forced type conversion. But JDK5.0 solves this problem nicely with generics, simplifying the use of ThreadLocal to some extent.

To recap, for multi-threaded resource sharing The synchronization mechanism uses a "time-for-space" approach, while ThreadLocal uses a "space-for-time" approach. The former provides only one copy of the variable for different threads to queue up to access, while the latter provides a copy of the variable for each thread, so it can be accessed simultaneously without affecting each other.

X. Why the act of spreading things?

XI. Introducing Spring's Thing Management

A transaction is a unified commit or rollback operation for a series of database operations (such as inserting multiple pieces of data); if the insertion succeeds, then it succeeds together, and if there is an exception in the middle, then all previous operations are rolled back. This will prevent dirty data and prevent problems with the database data.

Transaction management is generally done in development to avoid this situation。Spring It also has its own transaction management mechanism in, Generally. useTransactionMananger carry out manage, This can be done bySpring injection to accomplish this function。spring Several classes about transaction processing are provided:

TransactionDefinition // Transaction property definition

TranscationStatus // represents the current transaction, which can be committed, rolled back.

PlatformTransactionManager This isspring Provides the basis for managing transactions interface, Below it is an abstract class of implementationsAbstractPlatformTransactionManager, We use Transaction management classes such asDataSourceTransactionManager And so on are the subclasses of this class。

General Service Definition steps.

TransactionDefinition td =newTransactionDefinition();
TransactionStatus ts = transactionManager.getTransaction(td);
try{ 
    //do sth
    transactionManager.commit(ts);
}catch(Exception e){
    transactionManager.rollback(ts);
}

The transaction management provided by spring can be divided into two categories: programmatic and declarative.

Programmatic, which is more flexible, but code heavy and has more duplicate code.

The programming style mainly uses transactionTemplate. Omits some of the commit, rollback, and a series of transaction object definitions that need to be injected into the transaction management object. [Template mode is used here]

void add(){
    transactionTemplate.execute(newTransactionCallback(){
        pulic Object doInTransaction(TransactionStatus ts){
         //do sth
        }
    }
}

Declarative: declarative is more flexible than programmatic.

useTransactionProxyFactoryBean:PROPAGATION_REQUIRED PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly

enclosePoxy Dynamic agent The ability to commit and roll back transactions automatically

org.springframework.transaction.interceptor.TransactionProxyFactoryBean

PROPAGATION_REQUIRED-Supports the current transaction, and creates a new one if there is no current transaction. This is the most common option.

PROPAGATION_SUPPORTS-Supports the current transaction and executes as non-transactional if there is no current transaction.

PROPAGATION_MANDATORY-Supports the current transaction and throws an exception if there is no current transaction.

PROPAGATION_REQUIRES_NEW-New transaction, hangs the current transaction if it currently exists.

PROPAGATION_NOT_SUPPORTED-Executes the operation in a non-transactional manner, and hangs the current transaction if it currently exists.

PROPAGATION_NEVER-Executes in a non-transactional manner, throwing an exception if a transaction currently exists.

PROPAGATION_NESTED– If a transaction currently exists, is executed within a nested transaction。 If there are currently no transactions, is carried out withPROPAGATION_REQUIRED Similar operation。

XII. AOP

1. SaySpring of Type of notification What are they??

spring provides a total of five types of notifications.

Type of notification

interface

description

Around Notification

org.aopalliance.intercept.MethodInterceptor

Intercepting calls to target methods

Before Pre-notification

org.springframework.aop.MethodBeforeAdvice

Called before the target method call

After Post-notification

org.springframework.aop.AfterReturningAdvice

Called after the target method call

Throws exception notification

org.springframework.aop.ThrowsAdvice

Called when the target method throws an exception

<bean id="myMethodBeforeAdvice" class="com.cdtax.aop.MyMethodBeforeAdvice"></bean>
<!--  Configure post-notifications -->
<bean id="myAfterReturningAdvice" class="com.cdtax.aop.MyAfterReturningAdvice"></bean>
<!--  Configure the proxy object -->
<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean"> 
<!--  broker interface assemble -->
    <property name="proxyInterfaces">
        <list>
            <value>com.cdtax.aop.TestServiceInter</value>
            <value>com.cdtax.aop.TestServiceInter2</value>
        </list>
    </property>
    
    <!--  Weave notifications into the proxy object  |  The set of interceptor names-->
    <property name="interceptorNames">
        <list>
        <!--  The equivalent of putting MyMethodBeforeAdvice Pre-notifications are associated with proxy objects, We can also think of notifications as interceptors,struts2 The core is the interceptor -->
         <value>myMethodBeforeAdvice</value> 
                
        <!--  Weaving in post-notification -->
        <value>myAfterReturningAdvice</value>
                
        </list>
    </property>
    
    <!--  Configuring the Proxied Object, You can specify -->
    <property name="target" ref="test1Service">
        
    </property>
</bean>
</beans>

2. Talk about what is the difference between a target object implementing an interface and a target object not implementing an interface?

3. Please describe the difference between JDK dynamic proxy and CGLI proxy?

jdk A dynamic proxy is a target class that implements the interface, and cannot target the class;

A CGLI dynamic proxy is a target class that does not implement an interface. The main point is to generate a subclass of the specified class, overriding the methods in it.

4. Briefly explain what is the role of ProxyFactoryBean?

5. Describe the principle of auto-proxy in Spring?

5. Write what are the three elements that need to be specified to create a proxy object?

(1) Setting the target audience (2) Setting the proxy interface (3) Set the name of the interceptor

6. What are the two ways to write a proxy?

7. Please briefly describe: what is AOP? Brief description of AOP core?

9. Please describe the meaning of AOP transactions?

1. Please briefly describe the working mechanism of Spring?

2. Please answer why do you use Spring's working mechanism?

3. Please briefly describe what Spring is?

4. Briefly describe the components of spring?

5.Briefly describe what features are provided by the Spring container?

6. In Spring, there are several ways of bean injection and what is each?

7. Please briefly describe: the scope of Spring bean?

8. Describe the advantages of setting value injection?

9. Please describe the advantages of construct injection?

10. Name three ways in which bean factories create beans? 11. Please write the method for the life cycle of bean?

12. Please briefly describe your understanding of the IOC?

13. Please answer: what is the biggest benefit of IoC?

14. Briefly describe the types of IoC?

15. What is the difference between dependency injection and traditional programming in Spring?


Recommended>>
1、Free money for nothing man for man sign up
2、Cell Update Fluorescent labeling is out Google relies on algorithms to identify cell features without invasion
3、Jedi Quest development plans announced new maps new vehicles coming to improve fluidity
4、Shouguang City guard the ideological position to sing the main theme of development
5、Discounts for returning users Youre really naive

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号