The latest Java interview questions: Spring framework part

(*-*)浩
Release: 2019-11-09 15:05:49
Original
2450 people have browsed it

The latest Java interview questions: Spring framework part

1. How does SpringMVC work?

The user sends a request to the server, and the request is captured by the springMVC front-end controller DispatchServlet;

DispatcherServle parses the request URL, obtains the request resource identifier (URL), and then based on the URL Call HandlerMapping to map the request to the processor HandlerExcutionChain;

DispatchServlet selects a suitable HandlerAdapter adapter for processing based on the obtained Handler;

After the Handler completes the data processing, it will return a ModelAndView object to DisPatchServlet;

The ModelAndView returned by Handler is only a logical view and not a formal view. DispatcherSevlet uses ViewResolver to try to convert the logical view into a real view View;

DispatcherServle parses out the ModelAndView() through the model The parameters are parsed and finally the complete view is displayed and returned to the client;

The latest Java interview questions: Spring framework part

2. What are the common annotations of SpringMVC?

@RequestMapping is used to request url mapping.

@RequestBody annotation implements receiving json data of http request and converting json data into java object.

@ResponseBody annotation implements converting the object returned by the controller method into a json response to the customer.

3. How to enable the annotation processor and adapter?

In our projects, we usually turn on the annotation processor and adapter by turning on in springmvc.xml.

4. How to solve the problem of get and post garbled characters?

To solve the garbled post request: We can configure a CharacterEncodingFilter filter in web.xml. Set to utf-8. To solve the garbled code of get request: there are two methods. There are two solutions to the garbled Chinese parameters of the get request:

Modify the tomcat configuration file to add encoding consistent with the engineering encoding.

Another way to re-encode parameters String userName = new String(request.getParameter("userName").getBytes("ISO8859-1"), "utf-8");

5. Talk about your understanding of Spring?

Spring is an open source framework that is created to simplify enterprise-level application development. Spring can enable simple JavaBeans to achieve functions that only EJB could achieve before. Spring is an IOC and AOP container framework.

The main core of the Spring container is:

Inversion of Control (IOC). In the traditional Java development model, when an object is needed, we will use new ourselves Or getInstance, etc. directly or indirectly call the constructor to create an object. In the spring development model, the spring container uses the factory model to create the required objects for us. We do not need to create them ourselves. We can directly call the objects provided by spring. This is the idea of inversion of control.

Dependency injection (DI), spring uses the set method of the JavaBean object or the constructor method with parameters to automatically set its properties to the required values when we create the required object. This is the idea of dependency injection. .

Aspect-oriented programming (AOP), in the object-oriented programming (oop) idea, we extract things vertically into objects one by one. In aspect-oriented programming, we horizontally extract certain similar aspects of each object into an aspect, and perform some common operations on this aspect, such as permission control, transaction management, logging, etc. This is the idea of aspect-oriented programming. . The bottom layer of AOP is a dynamic proxy. If the interface uses JDK dynamic proxy, if the class uses CGLIB to implement dynamic proxy

6. What are the design patterns in Spring?

Single case mode - two proxy methods in spring. If the target object implements several interfaces, spring uses jdk's java.lang.reflect.Proxy class proxy. If the target implementation does not implement any interface, spring uses the CGLIB library to generate a subclass of the target class. Singleton mode - Set the bean to default to singleton mode in the spring configuration file.

Template mode mode - used to solve the problem of code duplication. For example: RestTemplate, JmsTemplate, JpaTemplate

Front-end controller mode - spring provides the front-end controller DispatherServlet to distribute requests.

View helper (viewhelper) - spring provides a series of JSP tags and efficient macros to help integrate scattered code into the view.

Dependency injection - the core concept that runs through the BeanFactory/ApplacationContext interface.

Factory Pattern - In the factory pattern, we do not expose the creation logic to the client when creating an object, and point to the newly created object by using the same interface. BeanFactory is used in Spring to create instances of objects.

7. Commonly used annotations of Spring?

Spring began to support annotations to configure dependency injection after version 2.5. Annotations can be used to replace bean descriptions in xml. Annotation injection will be processed by the container before XML injection, so the latter will overwrite the former's processing results for the same attribute.

Annotation assembly is turned off by default in spring. Therefore, you need to configure it in the spring core configuration file to use the annotation-based assembly mode. The configuration method is as follows:

Commonly used annotations:

@Required: This annotation applies to the value setting method.

@Autowired: This annotation applies to valued setter methods, non-setter methods, constructors and variables.

@Qualifier: This annotation is used in conjunction with @Autowired to disambiguate the automatic assembly of specific beans.

8. Briefly introduce the life cycle of spring beans?

Bean definition: used to define in the configuration file.

Bean initialization: There are two ways to initialize: This is done by specifying the init-method attribute in the configuration file. Implements the org.springframework.beans.factory.InitializingBean interface.

Bean calling: There are three ways to get the bean instance and call it.

Bean destruction: There are two ways to destroy: Use the destroy-method attribute specified in the configuration file. Implements org.springframework.bean.factory.DisposeableBean.

9. Do you understand the Spring structure diagram?

Core container: including Core, Beans, Context, and EL modules. Core module: Encapsulates the lowest level part of the framework dependencies, including resource access, type conversion and some common tool classes.

Beans module: Provides the basic part of the framework, including inversion of control and dependency injection. Among them, BeanFactory is the core of the container. It is essentially the implementation of the "factory design pattern" and does not require programming to implement the "single case design pattern". The single case is completely controlled by the container and advocates interface-oriented programming rather than implementation-oriented programming; all application objects And the relationships between objects are managed by the framework, which truly extracts the dependencies between maintained objects from the program logic. All these dependencies are maintained by BeanFactory.

Context module: Based on Core and Beans, it integrates Beans module functions and adds resource binding, data verification, internationalization, JavaEE support, container life cycle, event propagation, etc.; the core interface is ApplicationContext.

EL module: Provides powerful expression language support, supports accessing and modifying attribute values, method calls, supports accessing and modifying arrays, containers and indexers, named variables, supports arithmetic and logical operations, and supports running from Spring The container obtains the Bean, which also supports list projection, selection, and general list aggregation.

AOP, Aspects module: AOP module: Spring AOP module provides aspect-oriented programming (aspect-oriented programming) implementation that conforms to the AOPAlliance specification, providing common functions such as logging, permission control, performance statistics, etc. and business logic separation technology, and can dynamically add these functions to the required code; in this way, each one is dedicated to its own duties and reduces the coupling between business logic and general functions.

Aspects module: Provides integration of AspectJ. AspectJ provides more powerful functions than SpringASP. Data access/integration module: This module includes JDBC, ORM, OXM, JMS and transaction management.

Transaction module: This module is used for Spring management transactions. As long as Spring manages objects, they can get the benefits of Spring management transactions. There is no need to control transactions in the code, and it supports programming and declarative transaction management.

JDBC module: Provides a JBDC sample template. Using these templates can eliminate traditional lengthy JDBC coding and necessary transaction control, and you can enjoy the benefits of Spring's transaction management.

ORM module: Provides seamless integration with popular "object-relational" mapping frameworks, including Hibernate, JPA, MyBatis, etc. And you can use Spring transaction management without additional transaction control.

OXM module: Provides an Object/XML mapping implementation, mapping java objects into XML data, or mapping XML data into java objects. Object/XML mapping implementations include JAXB, Castor, XMLBeans and XStream.

JMS module: used for JMS (JavaMessagingService), providing a set of "message producer, message consumer" templates for simpler use of JMS. JMS is used between two applications. Or send messages in distributed systems for asynchronous communication. Web/Remoting module: The Web/Remoting module includes Web, Web-Servlet, Web-Struts, and Web-Porlet modules.

Web module: Provides basic web functions. For example, multiple file uploads, integrated IoC containers, remote process access (RMI, Hessian, Burlap) and WebService support, and a RestTemplate class is provided to provide convenient Restfulservices access.

Web-Servlet module: Provides a SpringMVCWeb framework implementation. The SpringMVC framework provides annotation-based request resource injection, simpler data binding, data validation, etc. and a set of very easy-to-use JSP tags, which completely seamlessly cooperates with other Spring technologies.

Web-Struts module: Provides seamless integration with Struts. Both Struts1.x and Struts2.x support the Test module: Spring supports Junit and TestNG testing frameworks, and also provides some additional testing functions based on Spring. , such as simulating the function of HTTP requests when testing web frameworks.

The latest Java interview questions: Spring framework part

#10. What can Spring help us do?

Spring can help us create and assemble dependencies between objects based on configuration files.

Spring creates and assembles dependencies between objects based on the configuration file. You only need to change the configuration file.

Spring aspect-oriented programming can help us implement logging without coupling. Performance statistics, security control.

Spring aspect-oriented programming can provide a better way to complete it, usually through configuration, and does not require adding any additional code to the existing code. The existing code focuses on business logic.

Spring can help us manage database transactions very simply.

Using Spring, we only need to obtain the connection and execute SQL, and other related things are managed by Spring.

Spring can also seamlessly integrate with third-party database access frameworks (such as Hibernate, JPA), and it also provides a set of JDBC access templates to facilitate database access.

Spring can also be seamlessly integrated with third-party Web (such as Struts, JSF) frameworks, and it also provides a set of SpringMVC framework to facilitate the construction of the web layer.

Spring can easily integrate with JavaEE (such as JavaMail, task scheduling) and integrate with more technologies (such as caching framework).

11. Please describe Spring’s transactions?

Definition of declarative transaction management: Use declarative transaction processing in Spring configuration files instead of code processing transactions. The advantage of this is that transaction management does not intrude into the developed components. Specifically, the business logic objects will not realize that they are being managed by the transaction. In fact, this should be the case, because transaction management is a service at the system level, not the business. As part of the logic, if you want to change the transaction management plan, you only need to reconfigure it in the definition file, which is extremely convenient to maintain.

Declarative transaction management based on TransactionInterceptor: two main attributes: transactionManager, used to specify a transaction manager and entrust specific transaction-related operations to it; the other one is the transactionAttributes attribute of the Properties type , in each key-value pair of this attribute, the key specifies the method name, the method name can use wildcards, and the value represents the transaction attribute used by the corresponding method.

 ......     PROPAGATION_REQUIRED               
Copy after login

Declarative transaction management based on TransactionProxyFactoryBean: Setting up the configuration file is much simpler than before. We call this type of setting configuration file format Spring's classic declarative transaction management.

 ......         PROPAGATION_REQUIRED    
Copy after login

Declarative transaction management based on namespace: Based on the first two methods, Spring 2.x introduces namespace and uses namespace in combination to bring developers the ability to configure declarative transactions. A new experience.

 ......             ...... 
Copy after login

Declarative transaction management based on @Transactional: Spring 2.x also introduces an Annotation-based approach, which mainly involves the @Transactional annotation. @Transactional can be applied to interfaces, interface methods, classes and class methods. When the calculation is applied to a class, all public methods of the class will have transaction attributes of that type.

@Transactional(propagation = Propagation.REQUIRED) public boolean transfer(Long fromId, Long toId, double amount) { return bankDao.transfer(fromId, toId, amount); }
Copy after login

The definition of programmatic transaction management: explicitly calling beginTransaction(), commit(), rollback() and other transaction management-related methods in the code, this is programmatic transaction management. Spring's programmatic management of things has two methods: programmatic management based on the underlying API and programmatic transaction management based on TransactionTemplate.

Programmatic management based on the underlying API: Credentials PlatformTransactionManager, TransactionDefinition and TransactionStatus three core interfaces to implement programmatic transaction management.

public class BankServiceImpl implements BankService { private BanckDao bankDao; private TransactionDefinition txDefinition; private PlatformTransactionManager txManager; public boolean transfer(Long fromId, Long toId, double amount) { TransactionStatus txStatus = txManager.getTransaction(txDefinition); boolean result = false; try { result = bankDao.transfer(fromId, toId, amount); txManager.commit(txStatus); } catch (Exception e) { result = false; txManager.rollback(txStatus); System.out.println("Transfer Error!"); } return result; } }
Copy after login

Programmatic transaction management based on TransactionTemplate: In order not to damage the original orderliness of the code and avoid the phenomenon that each method includes the same boilerplate code for starting things, submitting, and rolling back things, spring provides The transactionTemplate template is used to implement programmatic transaction management.

public class BankServiceImpl implements BankService { private BankDao bankDao; private TransactionTemplate transactionTemplate; public boolean transfer(final Long fromId, final Long toId, final double amount) { return (Boolean) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { Object result; try { result = bankDao.transfer(fromId, toId, amount); } catch (Exception e) { status.setRollbackOnly(); result = false; System.out.println("Transfer Error!"); } return result; } }); } }
Copy after login

The difference between programmatic transactions and declarative transactions:

Programmatic transactions are to write the transaction processing class yourself and then call it.

Declarative transactions are configured in the configuration file and are generally used in the framework.

The above is the detailed content of The latest Java interview questions: Spring framework part. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!