[Java interview five] Spring summary and some questions during the interview.

Source: Internet
Author: User

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

The concept of the IoC inverse of control inversion is to take control of the UserService object that was originally created in the program, to be managed by the spring framework, simply to say that the creation of UserService object control was reversed to the spring framework

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

Interview question: 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 a beanfactory extension that can be used for international processing, event delivery and bean Auto-assembly, as well as context implementations of various application tiers

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

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml")); IHelloService helloService = (IHelloService) beanFactory.getBean("helloService"); helloService.sayHello();What are the ways to instantiate a 3.spring configuration bean?

1) Instantiation with class constructor (default no parameter)

<bean id="bean1" class="cn.itcast.spring.b_instance.Bean1"></bean>2) instantiation with static Factory method (Simple Factory mode)

//下面这段配置的含义:调用Bean2Factory的getBean2方法得到bean2 <bean id="bean2" class="cn.itcast.spring.b_instance.Bean2Factory" factory-method="getBean2"></bean>3) Instantiation using instance Factory method (factory method mode)

Create a factory instance bean3facory, and then create a 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>4. Briefly describe the life cycle of spring?

1) in configuration <bean> elements, specify the bean's initialization method through Init-method, specifying the beans destruction method by Destroy-method

<beanid="lifeCycleBean"class="cn.itcast.spring.d_lifecycle.LifeCycleBean"init-method="setup"destroy-method="teardown"></bean>Issues to be aware of:

* Destroy-method only valid for scope= "singleton"

* Destroy method, must close the ApplicationContext object (manually called) before it is called

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); applicationContext.close();

2) Full life cycle of beans (11 steps) "Understand the content, but have some help with spring's internal operational understanding"

①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)

publicclassMyBeanPostProcessorimplementsBeanPostProcessor{ publicObject postProcessAfterInitialization(Object bean,String beanName) throwsBeansException{ System.out.println("第八步:后处理Bean,after初始化。"); //后处理Bean,在这里加上一个动态代理,就把这个Bean给修改了。 return bean;//返回bean,表示没有修改,如果使用动态代理,返回代理对象,那么就修改了。 } publicObject postProcessBeforeInitialization(Object bean,String beanName) throwsBeansException{ System.out.println("第五步:后处理Bean的:before初始化!!"); //后处理Bean,在这里加上一个动态代理,就把这个Bean给修改了。 return bean;//返回bean本身,表示没有修改。 } }Note: This pre-processing bean and the post-processing bean will intercept all the beans. ⑥ 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 Bean's life cycle and scope in the spring framework

(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

# #作用域


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.


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


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.


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? Spring supports constructor injection and setter method injection to constructor injection, through injection setter method injection through <constructor-arg> element, completion of injection "common way in development" through <property> element 7. What is What is the role of AOP,AOP?

Aspect-oriented programming (AOP) provides an alternative perspective for thinking about program structure, which makes up for the lack of object-oriented programming (OOP), which provides facets in addition to classes (classes). Modular, such as cross-cutting of multiple types and objects, to focus on the transaction management

One of the key components of spring is the AOP framework, which is free to choose whether to use AOP to provide declarative enterprise services, especially in lieu of EJB declarative services. The most important service is declarative transaction management, which is based on spring's abstraction of the management of things. Allowing users to implement custom facets, using AOP to refine the use of OOP, can think of spring AOP as an enhancement to spring

What are the core classes of 8.Spring and what are the roles?

Beanfactory: Create a new instance that can implement a singleton pattern

Beanwrapper: Provides a unified get and set method

ApplicationContext: Provides framework implementations, including all features of the beanfactory

9.Spring How to configure database driver? Use the "Org.springframework.jdbc.datasource.DriverManagerDataSource" data source to configure the database driver. Examples are as follows:
  1. <bean id=”dataSource”> 
  2.     <property name=”driverClassName”> 
  3. <value>org.hsqldb.jdbcDriver</value>
  4. </property>
  5.     <property name=”url”> 
  6.         <value>jdbc:hsqldb:db/appfuse</value> 
  7.     </property> 
  8.     <property name=”username”><value>abc</value></property> 
  9.     <property name=”password”><value>abc</value></property> 
  10. </bean> 
10.Spring inside Applicationcontext.xml file can be changed to other file name?

Contextloaderlistener is a servletcontextlistener that is initialized when your web app starts. By default, it will find spring's configuration in the Web-inf/applicationcontext.xml file. You can change the location of the spring configuration file by defining a <context-param> element named "Contextconfiglocation". Examples are as follows:

  1. <listener> 
  2.     <listener-class>org.springframework.web.context.ContextLoaderListener
  3.         <context-param> 
  4.          <param-name>contextConfigLocation</param-name> 
  5.          <param-value>/WEB-INF/xyz.xml</param-value> 
  6.         </context-param>   
  7.     </listener-class> 
  8. </listener> 
11.Spring How to define hibernate mapping?

Add Hibernate mapping files to the Applicationcontext.xml file in the Web/web-inf directory. Examples are as follows:

    1. <property name=”mappingResources”> 
    2.     <list> 
    3.         <value>org/appfuse/model/User.hbm.xml</value> 
    4.     </list> 
    5. </property>
12.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.

13. Why should there be an act of spreading things? 14. 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. }

Use transactionproxyfactorybean:propagation_required propagation_required propagation_required,readonly

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


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.

15. Explain some of the nouns in spring AOP

Facets (Aspect): A focus of modularity, which may be crosscutting across multiple objects. Transaction management is a good example of a crosscutting concern in the Java EE application. In spring AOP, facets can be implemented using generic classes (pattern-based styles) or @Aspect annotations (@AspectJ styles) in ordinary classes.

Connection point (Joinpoint): a particular point in the execution of a program, such as when a method is called or when an exception is handled. In spring AOP, a connection point always represents the execution of a method. By declaring a parameter of type Org.aspectj.lang.JoinPoint, you get the connection point information for the body part of the notification (Advice).

Notification (Advice): An action performed on a particular connection point (joinpoint) of a slice. Notifications are available in various types, including notifications such as "Around", "before", and "after". The type of notification is discussed later in this section. Many AOP frameworks, including spring, are notification models with interceptors, and maintain a chain of interceptors centered on the connection point.

Pointcut (Pointcut): an assertion that matches a connection point (Joinpoint). The notification is associated with a pointcut expression and runs on the connection point that satisfies the pointcut (for example, when a method for a particular name is executed). How Pointcut expressions match connection points is the core of AOP: Spring defaults to using the ASPECTJ pointcut syntax.

Introduced (Introduction): (also known as an internal type declaration (Inter-type declaration)). Declare additional methods or fields of a certain type. Spring allows the introduction of new interfaces (and a corresponding implementation) to any Proxied object. For example, you can use an introduction to make the bean implement the IsModified interface to simplify the caching mechanism.

Target object: An object that is notified (advise) by one or more facets (aspect). It is also called the notified (advised) object. Since spring AOP is implemented by the runtime proxy, this object is always a proxy (proxied) object.

AOP Proxy: An object created by the AOP framework to implement a facet contract (aspect contract), including functions such as notification method execution. In spring, an AOP proxy can be either a JDK dynamic agent or a cglib proxy. Note: The latest introduction to Spring 2.0 is the pattern-based (schema-based) style and @aspectj annotation style facet declarations, which are transparent to the users who use these styles.

Weaving (Weaving): Connects a facet (aspect) to another application type or object and creates an object that is notified (advised). These can be done at compile time (for example, with the AspectJ compiler), at class load time, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.

16. What are the types of notifications? Pre-notification (before advice): A notification 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): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally.
Notification after an exception is thrown (after throwing advice): the notification that is executed when the method throws an exception exits.
Post notification (after (finally) advice): A notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit).
Surround notification (Around Advice): A notification that encloses a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom 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 one of the most common types of notifications. Most interception-based AOP frameworks, such as Nanning and JBOSS4, provide only surround notifications.
The concept of pointcut (pointcut) and connection point matching is the key to AOP, which makes AOP different from other old technologies that simply provide interception functionality. The pointcut enables the location notification (advice) to be independent of the 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.

[Java interview five] Spring summary and some questions during the interview.

Related Article

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.