[Spring interview] Problem collation

Source: Internet
Author: User
Tags throwable

1. What is the difference between your understanding of the spring IOC and di?

Ioc:inverse of control inversion control is the concept of manually creating UserService objects in the program, which is managed by the spring framework,

Simply put, the creation of the UserService object control is reversed to the spring frame

Di:dependency injection Dependency Injection, which dynamically injects dependent objects into the bean component when the Spring framework is responsible for creating the Bean object

What is the difference between IoC and di?

IoC control inversion, which refers to the creation of objects, is reversed to the spring container, DI dependency injection, refers to the process of creating objects in spring, the object dependency properties are injected through the configuration

What is the difference between the 2.BeanFactory interface and the ApplicationContext interface? The ①applicationcontext interface inherits the Beanfactory interface, the Spring core factory is Beanfactory, Beanfactory takes a lazy load, and the bean is initialized the first time Getbean, ApplicationContext is the bean that will be initialized when the configuration file is loaded. ②applicationcontext is an extension to the beanfactory, with a detailed description of the difference:
International Treatment of Beanfactory is not supported for internationalization because Beanfactory does not extend the Messageresource interface in spring. Conversely, because ApplicationContext extends the Messageresource interface, it has the ability to process messages (i18n)
Event mechanism The ApplicationContext event mechanism is provided primarily through the two interfaces of Applicationevent and Applicationlistener, just like the event mechanism in Java swing. That is, when an event is published in ApplicationContext, all beans that extend the Applicationlistener will receive the event and handle it accordingly.

Spring provides some of the built-in events, mainly in the following ways:
When Contextrefreshedevent:applicationcontext sends this event, it means that all the beans in the container have been loaded and that the ApplicationContext is ready for use
Contextstartedevent: Start signal for life cycle beans
Contextstoppedevent: Stop signal for life cycle beans
Contextclosedevent:applicationcontext Shutdown event, the context cannot be refreshed and restarted, so all singleton beans are destroyed (because the singleton bean exists in the container cache)

Although spring provides many built-in events, users can also extend things in spring as they want. Note that the events to be extended are implemented with the Applicationevent interface.
Access to underlying resources ApplicationContext extends the Resourceloader (resource loader) interface, which can be used to load multiple resource, while Beanfactory is not extended Resourceloader
support for Web Apps and Beanfactory are typically programmatically created differently, ApplicationContext can be created declaratively, such as using Contextloader. Of course you can also use one of the ApplicationContext implementations to programmatically create a ApplicationContext instance.   

contextloader has two implementations: contextloaderlistener and contextloaderservlet . These two have the same functionality, except that listener cannot be used in servlet 2.2-compatible containers. Since the Servelt 2.4 specification, listener has been asked to initialize after the Web application is started. Many 2.3 compatible containers have implemented this feature. Which one you use depends on yourself, but if all the conditions are the same, you will probably prefer contextloaderlistener ; For more information on compatibility, refer to contextloaderservlet Javadoc.

This listener needs to check contextconfiglocation parameters. If it does not exist, it will use the /web-inf/applicationcontext.xml by default. If it exists , it separates the strings with a pre-defined delimiter (comma, semicolon, and space) and places the values as the application context will be searched. Contextloaderservlet can be used to replace Contextloaderlistener. This servlet uses the contextconfiglocation parameter like listener.

Other 1). Beanfactroy uses lazy loading as a way to inject beans, that is, only when a bean is used (called Getbean ()), the bean is loaded instantiated, so that we cannot discover some of the existing spring configuration problems. ApplicationContext, on the other hand, creates all the beans at once when the container is started. This way, when the container starts, we can discover the configuration errors that exist in spring.

2). Beanfactory and ApplicationContext both support the use of beanpostprocessor, beanfactorypostprocessor, but the difference between the two is: Beanfactory need to register manually, And ApplicationContext is automatically registered

The basic use of applicationcontext in development, Web projects using Webapplicationcontext, rarely used beanfactory.

What are the ways to instantiate a 3.spring configuration bean?

1) instantiating using the Class builder

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

2) instantiation with static Factory method (Simple Factory mode)

<id= "Bean2"  class= "Cn.itcast.spring.b_instance". Bean2factory "  factory-method=" getBean2 "></bean>

3) Instantiation using instance Factory method (factory method mode)

<id= "Bean3factory"  class= "Cn.itcast.spring.b_instance". Bean3factory "></bean><id=" Bean3 "  factory-bean=" Bean3factory "  factory-method=" GetBean3 " ></ Bean >
4. Briefly describe the life cycle of spring?

①instantiate Bean Object Instantiation

②populate Properties Package Property

③ if the bean implements Beannameaware execution Setbeanname

④ if the bean implements Beanfactoryaware or Applicationcontextaware sets the factory setbeanfactory or context object Setapplicationcontext

⑤ If there is a class implementation beanpostprocessor (post-processing bean), the execution Postprocessbeforeinitialization,beanpostprocessor interface provides a hook function to dynamically extend the modified bean. (program automatically calls post-processing bean)

⑥ if the bean implements Initializingbean execution Afterpropertiesset

⑦ call <bean init-method= "Init" > Specify initialization Method init

⑧ If there is a class implementation beanpostprocessor (Processing bean), execute postprocessafterinitialization

⑨ Performing Business Processing

⑩ if the bean implements Disposablebean execution destroy

Call <bean destroy-method= "Customerdestroy" > Specify Destruction Method Customerdestroy

5. Please describe the life cycle of the bean in the spring framework and the lifetime of the scope bean:

(1) Bean definition

The configuration file is defined with <bean></bean>.

(2) Bean initialization, there are two ways of initializing:

A. In the configuration file by specifying the Init-method property to complete

B. Implementing the Org.springframwork.beans.factory.InitializingBean Interface

(3) Bean call

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

(4) Bean destruction

There are two ways of destroying

A. Using the Destroy-method property specified by the configuration file

B. Implementing the Org.springframwork.bean.factory.DisposeableBean Interface

Scope of the Bean:

Singleton

When a bean is scoped to Singleton, there will only be one shared bean instance in the spring IOC container, and all requests to the bean will only return the same instance of the bean as long as the ID matches that bean definition.

Prototype

A prototype-scoped bean causes a new bean instance to be created each time the bean request is injected into another bean, or the Getbean () method of the container is called programmatically. Based on experience, you should use the prototype scope for all stateful beans, while for stateless beans you should use the singleton scope

Request

In an HTTP request, a bean definition corresponds to an instance, that is, each HTTP request will have its own bean instance, which is created from a bean definition. This scope is valid only in the case of a web-based spring ApplicationContext.

Session

In an HTTP session, a bean definition corresponds to an instance. This scope is valid only in the case of a web-based spring ApplicationContext.

Global session

In a global HTTP session, a bean definition corresponds to an instance. Typically, this is only valid when using the Portlet context. This scope is valid only in the case of a web-based spring ApplicationContext.

What are the different ways to inject 6.Bean properties?

constructor injection, completion of injection via <constructor-arg> element

Setter method injection, through <property> element completion injection "common way in development"

7. What is the role of AOP,AOP?

8.Spring How do I handle thread concurrency issues?

Spring uses threadlocal to resolve thread safety issues

We know that in general, only stateless beans can be shared in a multithreaded environment, and in spring, most beans can be declared as singleton scopes. Just because spring is on some beans (such as Requestcontextholder, Transactionsynchronizationmanager, Localecontextholder, etc.) The Central African thread-safe state is handled with threadlocal, making them also a thread-safe state, because stateful beans can be shared across multiple threads.

Both the threadlocal and thread synchronization mechanisms are designed to address the access violation of the same variable in multiple threads.

In the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult.

Threadlocal, however, solves multiple threads of concurrent access from another angle. Threadlocal provides a separate copy of the variable for each thread, isolating the access violation of multiple threads to the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects that can encapsulate unsafe variables into threadlocal when writing multithreaded code.

Because the threadlocal can hold any type of object, the Get () provided by the lower version of the JDK returns an object, which requires a type cast. But JDK5.0 solves this problem through generics and simplifies the use of threadlocal to some extent.

To sum up, for the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of "time-changing Space", and threadlocal adopts the way of "changing time by Space". The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

9. Introduction to Spring's things management

A transaction is a uniform commit or rollback operation for a series of database operations (such as inserting multiple data), and if the insert succeeds, it succeeds, and if there is an exception in the middle, all actions before the rollback. This prevents dirty data from occurring and prevents problems with database data.

In development, transaction management is generally done to avoid this situation. Spring also has its own transaction management mechanism, typically managed using Transactionmananger, which can be done through spring injection. Spring provides several classes for transaction processing:

Transactiondefinition//Transaction Property Definition

Transcationstatus//Represents the current transaction, which can be committed and rolled back.

Platformtransactionmanager This is the underlying interface that spring provides for managing transactions, under which there is an implementation of the abstract class Abstractplatformtransactionmanager, and the transaction management classes we use, such as Datasourcetransactionmanager and so on are subclasses of this class.

General Transaction definition steps:

    1. TransactionDefinition td =newTransactionDefinition();
    2. TransactionStatus ts = transactionManager.getTransaction(td);
    3. try{
    4. Do STH
    5.     transactionManager.commit(ts);
    6. }catch (Exception e) {
    7. Transactionmanager.rollback (TS);
    8. }
The transaction management that spring provides can be divided into two categories: programmatic and declarative. Programmatic, more flexible, but the code is large, there are more duplicate code, declarative more flexible than the programming type.

Programming mainly uses Transactiontemplate. Omit a partial commit, rollback, a series of transaction object definitions, to be injected into the transaction management object.

    1. void add(){
    2.     transactionTemplate.execute(newTransactionCallback(){
    3. Pulic Object dointransaction (transactionstatus ts) {
    4. Do STH
    5. }
    6.     }
    7. }
Declarative:

Use transactionproxyfactorybean:propagation_required propagation_required propagation_required,readonly

Dynamic agents around POxy are able to automatically commit and rollback transactions

Org.springframework.transaction.interceptor.TransactionProxyFactoryBean

propagation_required– supports the current transaction and creates a new transaction if there is no current transaction. This is the most common choice.

propagation_supports– supports the current transaction and is executed in a non-transactional manner if no transaction is currently in use.

The propagation_mandatory– supports the current transaction and throws an exception if there is no current transaction.

propagation_requires_new– a new transaction, suspending the current transaction if a transaction is currently present.

The propagation_not_supported– executes the operation in a non-transactional manner, suspending the current transaction if a transaction is currently present.

The propagation_never– is executed in a non-transactional manner and throws an exception if a transaction is currently present.

propagation_nested– executes within a nested transaction if a transaction is currently present. If there is currently no transaction, do something similar to propagation_required.

10. Explain some of the nouns in spring AOP

Example:

 PackageCore;Importjava.util.Arrays;Importjavax.servlet.http.HttpServletRequest;ImportOrg.apache.log4j.Logger;ImportOrg.aspectj.lang.JoinPoint;Importorg.aspectj.lang.annotation.AfterReturning;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;ImportOrg.aspectj.lang.annotation.Pointcut;Importorg.springframework.stereotype.Component;ImportOrg.springframework.web.context.request.RequestContextHolder;Importorg.springframework.web.context.request.ServletRequestAttributes;//defining a Java class as a slice class using @Aspect annotations@Aspect @component Public classWeblogaspect {PrivateLogger Logger =Logger.getlogger (GetClass ()); //use @Pointcut to define a pointcut, which can be a regular expression, such as all functions under a package in the following example, or an annotation. //TestController Execution of arbitrary methods@Pointcut ("Execution (* core. testcontroller.* (..)) ")     Public voidWebLog () {}//use @Before to cut into content at the beginning of a pointcut@Before ("WebLog ()")     Public voidDobefore (Joinpoint joinpoint)throwsThrowable {//receive request, log request contentServletrequestattributes attributes =(servletrequestattributes) requestcontextholder.getrequestattributes (); HttpServletRequest Request=attributes.getrequest (); //record the requested contentLogger.info ("URL:" +Request.getrequesturl (). toString ()); Logger.info ("Http_method:" +Request.getmethod ()); Logger.info ("IP:" +request.getremoteaddr ()); Logger.info ("Class_method:" + joinpoint.getsignature (). Getdeclaringtypename () + "." +joinpoint.getsignature (). GetName ()); Logger.info ("ARGS:" +arrays.tostring (Joinpoint.getargs ())); }    //use @AfterReturning to cut into content after pointcut return content (can be used to do some processing of processing return values)@AfterReturning (returning = "ret", pointcut = "WebLog ()")     Public voidDoafterreturning (Object ret)throwsThrowable {//after processing the request, return the contentLogger.info ("RESPONSE:" +ret); }}
Weblogaspect.java

Output log:

11. What are the types of notifications? Pre-notification (before advice): Anotification that is executed before a connection point, but this notification does not prevent execution before the connection point (unless it throws an exception). Notification after return (After returning advice): At a connection point (join point) after normal completion of the notification: for example, a method does not throw any exceptions, normal return.  
notifies when an exception is thrown (after throwing advice): the notification that is executed when the method throws an unexpected exit.  
Notification (after (finally) advice): A notification that is executed when a connection point exits (whether it is a normal return or an abnormal exit).  
Surround notification (around Advice): A notification that encloses a connection point (join points), such as a method call. This is the most powerful type of notification.   Surround Notifications You can customize the behavior before and after a method call. It also chooses whether to continue executing the connection point or to return directly to their own return value or throw an exception to end the execution.  
  
Surround notification is the most common type of notification. Most interception-based aop frameworks, such as nanning and jboss4, provide only surround notifications. &NBSP; The concept of
Pointcuts (pointcut) and connection points (join point) is the key to aop, This makes the aop different from other old technologies that simply provide interception capabilities.   Pointcuts make location notifications (advice) independent of oo hierarchy.   For example, a around notification that provides declarative transaction management can be applied to a set of methods that span multiple objects, such as all business operations at the service layer.

[Spring interview] Problem collation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.