Spring interview notes)

Source: Internet
Author: User

I. Working Principles of spring:

1. spring mvc requests all requests to be submitted to DispatcherServlet. It will entrust other modules of the application system to handle the requests in real time.
2. The DispatcherServlet queries one or more HandlerMapping and finds the Controller that processes the request.
3. Submit the DispatcherServlet request to the target Controller.
4. After the Controller processes the business logic, a ModelAndView is returned.
5. The Dispathcher queries one or more ViewResolver view Resolvers and finds the view object specified by the ModelAndView object.
6. view objects are rendered and returned to the client.
 

Ii. Why spring:

AOP allows developers to create non-behavioral concerns, known as cross-cutting concerns, and insert them into application code. With AOP, public services (such as logs, persistence, and transactions) can be decomposed into aspects and applied to domain objects without increasing the complexity of the Object Model of domain objects.

IOC allows you to create an application environment that can construct objects and then pass their collaboration objects to these objects. As the word inversion indicates, IOC is like the reversed JNDI. Instead of using a bunch of abstract factories, service locators, singleton, and straight construction, each object is constructed with its collaborative object. Therefore, collaborator is managed by containers ).

Even an AOP framework, Spring is also an IOC container. The best thing about Spring is that it helps you replace objects. With Spring, you only need to add dependencies (collaboration objects) with the JavaBean attribute and configuration file ). Then, you can easily replace a collaboration object with similar interfaces when needed.

3. Talk about SSH integration:

SSH:
Struts (presentation layer) + Spring (Business Layer) + Hibernate (persistence layer)
Struts:
Struts is a presentation layer framework. It mainly serves to display interfaces, receive requests, and distribute requests.
In the MVC Framework, Struts belongs to the VC level and is responsible for interface presentation and distribution of MVC relationships. (View: Follow JSP, HTTP, Form, Tag, Resourse; Controller: ActionServlet, struts-config.xml, Action)
Hibernate:
Hibernate is a persistent layer framework that is only responsible for operations with relational databases.
Spring:
Spring is a service-layer framework and an integrated framework that can be well attached to the presentation layer and persistence layer.

4. Introduce Spring's transaction management:

A transaction is a unified commit or rollback operation on a series of database operations (such as inserting multiple data records). If the insertion is successful, the operation succeeds together. If one of the operations has an exception, all operations before rollback.
This prevents dirty data and database data problems.
In development, transaction management is generally performed to avoid this situation. Spring also has its own transaction management mechanism, which is generally managed using TransactionMananger. This function can be completed through Spring injection.

Spring provides several classes for transaction processing:
TransactionDefinition // transaction attribute Definition
TranscationStatus // indicates the current transaction, which can be committed and rolled back.
PlatformTransactionManager is the basic interface provided by spring for managing transactions. There is an implementation abstract class AbstractPlatformTransactionManager under it. The transaction management class we use, such as cetcetransactionmanager, is a subclass of this class.

General transaction definition steps:

TransactionDefinition td = new TransactionDefinition ();
TransactionStatus ts = transactionManager. getTransaction (td );
Try
{// Do something
TransactionManager. commit (ts );
}
Catch (Exception e) {transactionManager. rollback (ts );}

Spring provides two types of transaction management: programmatic and declarative. Programming, flexible, but with a large amount of code, there are more repeated code; declarative is more flexible than programming.

The main programming method is transactionTemplate. Some commit, rollback, and a series of transaction object definitions are omitted, and transaction management objects need to be injected.
Void add (){
TransactionTemplate.exe cute (new TransactionCallback (){
Pulic Object doInTransaction (TransactionStatus ts)
{// Do something}
}
}

Declarative:

Use TransactionProxyFactoryBean:
PROPAGATION_REQUIRED, readOnly

 

The dynamic proxy around Poxy can automatically commit and roll back transactions.
Org. springframework. transaction. interceptor. TransactionProxyFactoryBean

PROPAGATION_REQUIRED-supports the current transaction. If no transaction exists, a new transaction is created. This is the most common choice.

PROPAGATION_SUPPORTS-supports the current transaction. If no transaction exists, it is executed in non-transaction mode.

PROPAGATION_MANDATORY-supports the current transaction. If no transaction exists, an exception is thrown.

PROPAGATION_REQUIRES_NEW-creates a transaction. If a transaction exists, it is suspended.

PROPAGATION_NOT_SUPPORTED-executes operations in non-transactional mode. If a transaction exists, the current transaction is suspended.

PROPAGATION_NEVER-runs in non-transaction mode. If a transaction exists, an exception is thrown.

PROPAGATION_NESTED-if a transaction exists, it is executed within the nested transaction. If no transaction exists, perform a similar operation as PROPAGATION_REQUIRED.

5. How to configure the database driver in Spring?

Use the org. springframework. jdbc. datasource. DriverManagerDataSource data source to configure the database driver. Example:
<Bean id = "dataSource">
<Property name = "driverClassName">
<Value> org. hsqldb. jdbcDriver </value>
</Property>
<Property name = "url">
<Value> jdbc: hsqldb: db/appfuse </value>
</Property>
<Property name = "username"> <value> sa </value> </property>
<Property name = "password"> <value> </property>
</Bean>

6. Can I change the applicationContext. xml file in Spring to another file name?

ContextLoaderListener is a ServletContextListener, Which is initialized when your web application starts. By default, it looks for the Spring configuration in the WEB-INF/applicationContext. xml file. You can change the position of the Spring configuration file by defining the <context-param> element named "contextConfigLocation. Example:

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

7. How to configure spring in web applications?

Add the following content to web. xml to load the content in/WEB-INF/applicationContext. xml when the web server is started.
<Servlet>
<Servlet-name> context </servlet-name>
<Servlet-class>
Org. springframework. web. context. ContextLoaderServlet
</Servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
Obtain the ApplicationContext instance using the following class:
WebApplicationContextUtils. getWebApplicationContext

8. How to define hibernate mapping in Spring?

Add the hibernate mapping file to the applicationContext. xml file under the web/WEB-INF directory. Example:
<Property name = "mappingResources">
<List>
<Value> org/appfuse/model/User. hbm. xml </value>
</List>
</Property>

9. What is Dependency injection (DI, Dependency injection) and IOC (Inversion of control, control reversal )?

Dependency injection DI is a program design model and architecture model, which is also called control inversion in some cases. Although technically, dependency injection is a special implementation of IOC, dependency injection refers to the application of another object to provide a special capability. For example: upload a database connection parameter to the structure method of an object instead of creating a connection within the object. The basic idea of controlling inversion and dependency injection is to convert class Dependencies from inside to outside to reduce dependencies.
Application Control inversion: when an object is created, the external entities of all objects in a control system reference the objects it depends on and pass them to it. It can also be said that the dependency is injected into the object. Therefore, the inversion of control is about how an object obtains the reference of the object on which it depends, and the reversal of this responsibility.

10. What are the roles of BeanFactory and ApplicationContext in spring?

1. BeanFactory is responsible for reading bean configuration documents, managing bean loading and instantiation, maintaining dependencies between beans, and declaring bean cycles.
2. ApplicationContext not only provides the functions provided by BeanFactory, but also provides a more complete framework function:

A. International support
B. Resource Access: Resource rs = ctx. getResource ("classpath: config. properties"), "file: c:/config. properties"
C. Event transfer: implement the ApplicationContextAware Interface
3. common methods for obtaining ApplicationContext:
FileSystemXmlApplicationContext: created from the xml configuration file specified by the file system or url. The parameter is the configuration file name or file name array.
ClassPathXmlApplicationContext: created from the xml configuration file of classpath. You can read the configuration file from the jar package.
WebApplicationContextUtils: to read the configuration file from the root directory of the web application, you must first configure it in web. xml. You can configure the listener or servlet to implement
<Listener>
<Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class>
</Listener>
<Servlet>
<Servlet-name> context </servlet-name>
<Servlet-class> org. springframework. web. context. ContextLoaderServlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
Both methods use the default configuration file web-inf/applicationContext. xml. You can also use context-param to specify the configuration file.
<Context-param>
<Param-name> contextConfigLocation </param-name>
<Param-value>/WEB-INF/myApplicationContext. xml </param-value>
</Context-param>

11. how to configure the applicationContext. xml file in the web environment?

<Listener>
<Listener-class>
Org. springframework. web. context. ContextLoaderListener
</Listener-class>
</Listener>
Or:
<Servlet>
<Servlet-name> context </servlet-name>
<Servlet-class>
Org. springframework. web. context. ContextLoaderServlet
</Servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
Use the following method to retrieve the applicationContext instance:
ApplicationContext ac = WebApplicationContextUtils. getWebApplicationContext (this. getServletContext );

12. how to configure spring + struts?

Add a plug-in the struts-config.xml to load applicationContext. xml through it
Modify the action-mapping tag in the struts-config.xml, the specific action is given to DelegateActionProxy
Ingress enters a spring environment through DelegateActionProxy.
Add <bean name = "/login" class = "" singleton = "false"/> to spring applicationContext. xml.

13. What are the main classes in the spring + hibernate configuration file? How to configure it?

DataSource
SessionFactory: hibernate. cfg. xml
TransactionManager
UserDao (extends HibernateDaoSupport)
SessionFactory
Facade
Proxy
SessionFactory
TransactionManager
Facade

Add the spring environment to myeclipse and then the hibernate environment.
If spring and hibernate are combined, you do not need to check whether the hibernate. cfg. xml file is correct.

14. How to internationalize in spring?

Load a bean in applicationContext. xml
<Bean id = "messageSource" class = "org. springframework. context. support. ResourceBundleMessageSource">
<Property name = "basename">
<Value> message </value>
</Property>
</Bean>
Multiple properties files are created in the src directory.
For non-English users, use native2ascii-encoding gb2312 as the source object to convert the file content.
The naming format of country is message _ language _ country.
A prompt is displayed on the keys page.
When a country is specified, the system automatically loads the properties information of the country.
Using applictionContext. getMessage ("key name", "parameter", "region") to retrieve relevant information.

15. What are the core classes in spring?

BeanFactory: generate a new instance and implement the singleton mode.
BeanWrapper: provides unified get and set methods.
ApplicationContext: Provides Framework implementation, including all BeanFactory functions.

16. What is aop and what is the role of aop?

Aspect-oriented programming (AOP) provides another way to think about the program structure. In this way, it makes up for the shortcomings of Object-Oriented Programming (OOP ).
In addition to classes, AOP provides a cut surface. This module modularize the focus, such as cross-cutting transaction management for multiple types and objects.
A key component of Spring is the AOP framework. You can choose whether to use AOP.
It provides declarative enterprise services, especially to replace EJB declarative services. The most important service is declarative transaction management, which is built on Spring's abstract transaction management.
Allows users to implement custom aspect and use AOP to improve the use of OOP
We can regard Spring AOP as an enhancement to Spring.

17. What are the advantages of using Spring?

◆ Spring can effectively organize your intermediate layer objects, whether or not you choose to use EJB. If you only use Struts or other frameworks that contain the APIs specific to J2EE, you will find that Spring is concerned with the issues left behind ,.

◆ Spring can eliminate the excessive use of Singleton in many projects. Based on my experience, this is a major problem, which reduces the testability and object-oriented features of the system.
◆ Spring can eliminate the need for custom attributes in various formats, and can be configured in a consistent way throughout the application and project. I was once confused that a specific class had to read Javadoc or even the source code to find the keyword or system attribute of a phantom attribute? With Spring, you can easily see the JavaBean attribute of the class. The use of inverted control (discussed below) helps with this simplification.
◆ Spring can promote good programming habits through interfaces rather than classes, reducing the programming cost to almost zero.
◆ Spring is designed to minimize the reliance on its APIs for Applications created using it. Most business objects in Spring applications do not depend on Spring.
◆ Applications built using Spring are easy to perform unit tests.
◆ Spring makes the use of EJB an implementation choice, rather than an Inevitable Choice of application architecture. You can use POJOs or local EJBs to implement business interfaces without affecting the calling code.
◆ Spring helps you solve many problems without using EJB. Spring can provide an EJB replacement, which is suitable for many web applications. For example, Spring can use AOP to provide declarative transactions instead of using EJB containers. If you only need to deal with a single database, you do not even need to implement JTA.
■ Spring provides a consistent framework for data access, whether using JDBC or O/R mapping products (such as Hibernate ).
Spring does allow you to solve your problem through the simplest and most feasible solution. These features are of great value.
To sum up, Spring has the following advantages:
◆ Low intrusive design with extremely low code pollution
◆ Independent from various application servers, can truly implement the commitment of Write Once and Run Anywhere
◆ The di mechanism of Spring reduces the complexity of Business Object replacement.
◆ Spring is not completely dependent on Spring. Developers are free to choose some or all of the Spring frameworks.

18. What is Spring? What are its characteristics?

Spring is a lightweight container framework for IoC and AOP.

◆ Lightweight-Spring is lightweight in terms of size and overhead. The complete Spring framework can be published in a JAR file with a size of more than 1 MB. And the processing overhead required by Spring is negligible. In addition, Spring is non-intrusive: Typically, objects in Spring applications do not depend on specific classes of Spring.

◆ Control inversion-Spring promotes loose coupling through a technology called control inversion (IoC. When IoC is applied, other objects that an object depends on will be passed in passively, instead of creating or searching for dependent objects. You can think that IoC is the opposite of JNDI-it is not that the object searches for Dependencies from the container, but that the container actively passes the dependency to the object request during object initialization.
◆ Aspect-Oriented -- Spring provides rich support for Aspect-Oriented Programming, which allows you to manage business logic and system-level services (such as audit and transaction) of applications by separating them) for cohesion development. Application objects only implement what they should do -- complete the business logic -- that's all. They are not responsible (or even conscious) for other system-level concerns, such as log or transaction support.
◆ Container -- Spring contains and manages the configuration and lifecycle of application objects. In this sense, Spring is a container, you can configure how each of your beans is created-based on a configurable prototype ), your bean can create a separate instance or generate a new instance every time you need it-and how they are associated. However, Spring should not be mixed with traditional heavyweight EJB containers, which are often large and bulky and difficult to use.
◆ Framework-Spring can configure and combine simple components into complex applications. In Spring, application objects are declared and combined, typically in an XML file. Spring also provides many basic functions (such as transaction management and persistent framework integration), leaving the development of application logic to you.

19. Introduce the Bean lifecycle in the Spring framework

I. Bean Definition
Spring usually defines beans through the configuration file. For example:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Beans xmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd”>
<Bean id = "HelloWorld" class = "com. pqf. beans. HelloWorld">
<Property name = "msg">
<Value> HelloWorld </value>
</Property>
</Bean>
</Beans>

This configuration file defines a Bean marked as HelloWorld. Multiple beans can be defined in a configuration document.

Ii. Bean Initialization
Two methods are available for Bean initialization.
1. Specify the init-method attribute in the configuration document.
Implement a method to initialize Bean attributes in Bean classes, such as init (), for example:
Public class HelloWorld {
Public String msg = null;
Public Date date = null;

Public void init (){
Msg = "HelloWorld ";
Date = new Date ();
}
......
}
Then, set the init-mothod attribute in the configuration file:
<Bean id = "HelloWorld" class = "com. pqf. beans. HelloWorld" init-mothod = "init">
</Bean>

2. Implement the org. springframwork. beans. factory. InitializingBean interface.
Bean implements the InitializingBean interface and adds the afterPropertiesSet () method:

Public class HelloWorld implement InitializingBean {
Public String msg = null;
Public Date date = null;

Public void afterPropertiesSet (){
Msg = "Hello to the world !";
Date = new Date ();
}
......
}

When all attributes of this Bean are set by BeanFactory of Spring, the afterPropertiesSet () method is automatically called to initialize the Bean, you do not need to specify the init-method attribute in the configuration file.

Iii. Bean call
There are three ways to obtain and call the Bean:
1. Use BeanWrapper
HelloWorld hw = new HelloWorld ();
BeanWrapper bw = new BeanWrapperImpl (hw );
Bw. setPropertyvalue ("msg", "HelloWorld ");
System. out. println (bw. getPropertyCalue ("msg "));

2. Use BeanFactory
InputStream is = new FileInputStream ("config. xml ");
XmlBeanFactory factory = new XmlBeanFactory (is );
HelloWorld hw = (HelloWorld) factory. getBean ("HelloWorld ");
System. out. println (hw. getMsg ());

3. Use ApplicationConttext
ApplicationContext actx = new FleSystemXmlApplicationContext ("config. xml ");
HelloWorld hw = (HelloWorld) actx. getBean ("HelloWorld ");
System. out. println (hw. getMsg ());

Iv. Bean destruction
1. Use the destory-method attribute in the configuration file
Similar to the initialization attribute init-methods, you can implement a Bean revocation method in the Bean class and specify the method in the configuration file through destory-method. When the bean is destroyed, spring automatically calls the specified destruction method.

2. Implement the org. springframwork. bean. factory. DisposebleBean interface.
If the DisposebleBean interface is implemented, Spring will automatically call the Destory method in bean for destruction. Therefore, the Destory method must be provided in Bean.

20. Several important terms and concepts in AOP:

Aspect (Aspect): modularity of a focus, which may cross multiple objects. Transaction Management is a good example of cross-cutting concerns in J2EE applications. In Spring AOP, a common class (pattern-based style) or @ Aspect annotation (@ AspectJ style) can be used for the Aspect.

Joinpoint: a specific point during program execution, 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 an org. aspectj. lang. JoinPoint parameter, you can obtain the connection point information for the main part of the notification (Advice.

Advice: The action performed on a specific connection point (Joinpoint) of a plane. There are various types of notifications, including "around", "before", and "after. The notification type will be discussed later. Many AOP frameworks, including Spring, use interceptor as the notification model and maintain a connection point-centric interceptor chain.

Pointcut: an assertion that matches the Joinpoint. A notification is associated with an entry expression and runs on the connection point that meets the entry expression (for example, when a method with a specific name is executed ). How the entry point expression matches the connection point is the core of AOP: Spring uses the AspectJ entry point syntax by default.

Introduction: (also known as 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 proxy object. For example, you can use an introduction to implement the IsModified interface of bean to simplify the cache mechanism.

Target Object: The Object notified by one or more aspect. Someone also calls it an advised object. Since Spring AOP is implemented through runtime, this object is always a proxied object.

AOP Proxy: an object created by the AOP framework to implement aspect contract (including notification method execution and other functions ). In Spring, the AOP proxy can be JDK dynamic proxy or CGLIB proxy. Note: The newly introduced schema-based style and @ AspectJ annotation style statement in Spring 2.0 are transparent to users who use these styles.

Weaving: connects an aspect to another application type or object and creates an advised object. These can be completed at compilation (for example, using the AspectJ compiler), class loading and runtime. Like other pure Java AOP frameworks, Spring completes weaving at runtime.

Notification Type:

Before advice: a notification that is executed Before a join point. However, this notification cannot be executed Before a connection point (unless it throws an exception ).

After returning advice: the notification that is executed After a join point is completed normally. For example, a method does not throw any exception and returns normally.

After throwing advice: the notification that is executed when the method throws an exception and exits.

After notification (finally) advice: the notification executed when a connection point exits (whether it is a normal return or an abnormal exit ).

Around Advice: a notification that surrounds a join point, such as a method call. This is the most powerful notification type. Surround notifications can complete custom actions before and after method calls. It will also choose whether to continue executing the connection point or directly return their own return values or throw an exception to end the execution.

Surround notification is the most common notification type. Most of the interception-based AOP frameworks, such as Nanning and JBoss4, only provide surround notifications.

The concept of point cut matching and join point matching is the key of AOP, which makes AOP different from the old technology that only provides the Interception Function. The entry point allows the positioning notification (advice) to be independent from the OO level. For example, an round robin notification that provides declarative transaction management can be applied to a group of methods across multiple objects (for example, all business operations at the service layer ).
Author: yy008871

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.