preface

Many friends ask, how short time assault Java through the interview?

Before the interview is still necessary to targeted brush some questions, many friends of the actual combat ability is very strong, but the theory is weak, do not prepare before the interview is very at a disadvantage. Here is a list of interview questions that can help you review before the interview and find a good job. It also saves you the time of searching for information on the Internet.

Spring, Spring MVC, Spring Boot, Mybatis MySQL, Redis, messaging middleware MQ, Distributed and microservices. Continuously updated…

The full version of Java interview questions address: 105 Java interview questions summary | including parsing the answers

content address
Java based Juejin. Cn/post / 694825…
Multithreading and concurrency Juejin. Cn/post / 694933…
Spring In this paper,
Spring MVC, Spring Boot Not updated
MyBatis Not updated
MySQL Not updated
Redis Not updated
Distributed and microservices Not updated
MQ Not updated

How do I implement an IOC container

1. Configure the packet scanning path in the configuration file

2. Recursive package scanning to obtain. Class files

3. Reflect and identify classes that need to be handed over to IOC management

4. Perform dependency injection on the classes to be injected

(1) specified in the configuration file needs to scan the package path (2) define some annotations, respectively access control layer, business service layer, data persistence layer, dependency injection annotations, obtain annotations (3) the configuration file from a configuration file needs to scan the package path, access to the current path of files and folders information, We will all in the current path. The class at the end of the file is added to a collection of the Set of storage (4) traverse the Set Set, annotations specified in the class have a class, and hand it over to the IOC container, define a security Map is used to store these objects (5) through the IOC container, access to each instance of a class, Determine if there are instances of classes that depend on other classes, and then perform recursive injection

What is Spring?

A lightweight open source J2EE framework. It is a container framework, used to hold Javabeans (Java objects), the middle layer framework (universal glue) can play a role of connection, such as Struts and Hibernate glue together to use, can make our enterprise development faster and more concise

Spring is a lightweight Inversion of Control (IoC) and section-oriented (AOP) container framework (1) Spring is lightweight in terms of size and overhead. (2) Loose coupling through inversion of control (IoC) techniques (3) rich support for section-oriented programming, allowing cohesive development by separating application business logic from system-level services (4) containing and managing the configuration and life cycle of application objects (beans), in this sense a container. (5) It is a framework to configure and combine simple components into complex applications.

Talk about your understanding of AOP

A system is made up of many different components, each responsible for a specific piece of functionality. These components often take on additional responsibilities in addition to implementing their core functions. Core services such as logging, transaction management, and security are often integrated into components that have their own core business logic. These system services are often referred to as crosscutting concerns because they span multiple components of the system.

OOP is helpless when we need to introduce common behavior to discrete objects. That is, OOP allows you to define top-to-bottom relationships, but not left-to-right relationships. For example, the logging function.

Logging code tends to be spread horizontally across all object hierarchies, regardless of the core functionality of the object to which it is spread.

In OOP design, it leads to a lot of code duplication, which is not conducive to reuse of modules.

AOP: Encapsulate the cross-cutting business logic in a program (such as security, logging, transaction, etc.) into a facet that is then injected into the target object (concrete business logic). AOP can enhance an object or its functionality by, for example, enhancing methods in an object to do extra things before or after a method is executed.

Talk about your understanding of IOC

Container concepts, inversion of control, dependency injection

The ioc container

It is actually a map (key, value) containing various objects (bean nodes configured in XML, @repository, @service, @Controller, @Component). The bean nodes in the configuration file will be read at project startup. Use reflection to create objects based on the fully qualified class name, scan to the class annotated above, or use reflection to create objects and put them into the map.

At this point, there are various objects in the map, and then we need to use the objects in the code, through DI injection (autowired, Resource, etc.), the ref attribute in the bean node in XML, when the project starts, the XML node ref attribute will be read according to the ID injection, and these annotations will also be scanned. Injection by type or ID; Id is the object name).

Inversion of control

Before the IOC container was introduced, object A depended on object B, so object A had to take the initiative to create object B or use the already created object B when it was initialized or run to A certain point. Whether you create or use object B, you have control.

After the introduction of IOC container, the direct connection between object A and object B is lost. When object A runs and needs object B, IOC container will take the initiative to create an object B and inject it into the place that object A needs.

It is not hard to see from the comparison: the process by which object A acquires dependent object B changes from active to passive, and control is reversed, hence the name “inversion of control”.

All turned over control of all objects to “third party” the IOC container, so, the IOC container has become the key to the core of the whole system, it plays a role of a similar “glue” that holds together all the objects in the system to work, without the “glue”, between the object and the object will lose touch with each other, This is why some people describe the IOC container as a glue.

Dependency injection

“The process of obtaining dependent objects is reversed.” When control is reversed, the process of obtaining dependent objects is changed from self-management to active injection by the IOC container. Dependency injection is the way to implement IOC, in which the IOC container dynamically injects certain dependencies into objects at run time.

What’s the difference between BeanFactory and ApplicationContext?

ApplicationContext is a subinterface of the BeanFactory

ApplicationContext provides more complete functionality: ① Inherits MessageSource and therefore supports internationalization. ② Unified access mode of resource files. ③ Provide the event to register the bean in the listener. 4. Load multiple configuration files at the same time. (5) Load multiple (inheritable) contexts so that each context is focused on a specific layer, such as the web layer of the application.

BeanFactroy uses lazy loading to inject beans, meaning that a Bean is loaded and instantiated only when it is used (by calling getBean()). This way, we won’t be able to find some existing Spring configuration issues. If a property of the Bean is not injected, the BeanFacotry load does not throw an exception until the first use of the getBean method.

ApplicationContext, which creates all the beans at once when the container is started. This way, we can find configuration errors in Spring when the container starts, which makes it easier to check whether the dependent properties are injected.

By preloading singleton beans after the ApplicationContext starts, you ensure that you don’t have to wait for them to be created when you need them.

The only disadvantage of the ApplicationContext relative to the basic BeanFactory is that it takes up memory. When an application has many configured beans, the application starts slowly.

BeanFactory is usually created programmatically, and ApplicationContext can also be created declaratively, such as using ContextLoader. BeanFactory and ApplicationContext both support the use of BeanPostProcessor and BeanFactoryPostProcessor, but the difference between them is: BeanFactory needs to be registered manually, whereas ApplicationContext is automatically registered.

Describe the life cycle of Spring beans?

1. Parse the class to get a BeanDefinition

2. If there are multiple constructors, infer the constructor

3. After determining the constructor, instantiate to get an object

4. Fill the @autoWired annotated property in the object

5. Call back Aware methods such as BeanNameAware and BeanFactoryAware

6. Call BeanPostProcessor’s pre-initialization method

7. Call the initialization method

Call BeanPostProcessor’s initialized method, where AOP will be applied

9. If the currently created bean is a singleton, the bean is added to the singleton pool

10. Use beans

11. Call the destory() method to DisposableBean when the Spring container closes

Explain the scope of several beans supported by Spring.

singleton

By default, there is only one instance of a bean per container, and the singleton pattern is maintained by the BeanFactory itself. The life cycle of this object is consistent with the Spring IOC container (but is created when it is first injected).

prototype

Provide one instance for each bean request. A new object is created at each injection

request

The bean is defined to create a singleton in each HTTP request, meaning that this singleton is reused in a single request.

session

Similar to the Request scope, it ensures that there is an instance of a bean in each session and that the bean is invalidated after the session expires.

application

The bean is defined to reuse a singleton object in the lifetime of the ServletContext.

websocket

A bean is defined to reuse a singleton object over the life of a Websocket.

global-session

Global scope, global-session is relevant to Portlet applications. When your application is deployed to work in a Portlet container, it contains many portlets. If you want to declare that all portlets share global stored variables, the global variables need to be stored in global-session. The global scope has the same effect as session scope in the Servlet.

Are singleton beans in the Spring framework thread-safe?

Beans in Spring are singleton by default, and the framework does not encapsulate beans in multiple threads.

If the Bean is stateful, it is up to the developer to ensure thread-safety. The simplest way is to change the scope of the Bean to “protopyte” instead of “singleton” so that each request to the Bean is a new Bean(), thus ensuring thread-safety

(1) Stateful means there is data storage function

The Controller, Service, and DAO layers themselves are not thread-safe, but if only the methods inside are called, and multiple threads call the methods of an instance, variables will be copied in memory, which is the working memory of their own threads, so it is safe.

Daos operate on database connections, which have state, such as database transactions. Spring’s transaction manager maintains a separate set of Connection copies for different threads using Threadlocal. Ensure that threads do not affect each other (how does Spring ensure that transactions acquire the same Connection)

Do not declare any stateful instance or class variables in the bean. If you must, use ThreadLocal to make the variables thread-private. If the bean’s instance or class variables need to be shared between multiple threads, Synchronized, lock, CAS, and so on are the only ways to implement thread synchronization.

What design patterns are used in the Spring framework?

Simple factory

A factory class dynamically decides which product class should be created based on the parameters passed in.

The BeanFactory in Spring is an embodiment of the simple factory pattern. Bean objects are obtained by passing in a unique identifier, but whether this is created after or before the parameters are passed in depends on the case.

The factory method

Beans that implement the FactoryBean interface are a class of beans called Factory. The trick is that spring automatically calls the bean’s getObject() method when it gets the bean using the getBean() call, so instead of returning the factory bean, it returns the value of the bean.getojbect () method.

The singleton pattern

Ensure that a class has only one instance and provide a global access point to access it

Spring’s implementation of singletons: The singleton pattern in Spring does the rest, providing a global access point to the BeanFactory. But you don’t control the singleton from the constructor level, because Spring manages arbitrary Java objects.

Adapter mode

Spring defines an adaptation interface so that each Controller has a corresponding adapter implementation class that performs the corresponding methods instead of the Controller. When you extend Controller, you only need to add an adapter class to complete the extension of SpringMVC.

## Decorator mode

Add some extra responsibilities to an object dynamically. The Decorator pattern is more flexible in terms of adding functionality than subclassing. The Wrapper pattern used in Spring has two representations on class names: one with a Wrapper in the class name and one with a Decorator in the class name.

A dynamic proxy

The facets are woven in at the time the application runs. Typically, the AOP container dynamically creates a proxy object for the target object when weaving into the cut. SpringAOP is woven into the facets in this way. Weaving: The process of applying a facet to a target object and creating a new proxy object.

Observer model

Spring’s event-driven model uses the Observer pattern, and a common place in Spring for the Observer pattern is the listener implementation.

The strategy pattern

The Spring framework’s Resource access Resource interface. This interface provides greater access to resources, and the Spring framework itself makes extensive use of the Resource interface to access underlying resources.

Template method

The parent class defines the skeleton (which methods to call and in what order), and certain methods are implemented by subclasses.

The biggest benefit

Code reuse, reduce duplicate code. Methods and the order in which they are called are written in advance in the parent class, except for the specific methods that the subclass implements.

The refresh method

How and why are Spring transactions implemented and isolated?

When using the Spring framework, there are two ways to use transactions, programmatic and declarative. The @Transactional annotation is declarative.

First, the concept of transactions is database-level, and Spring just extends it and provides ways to make it easier for programmers to manipulate transactions.

For example, you can start a transaction by adding the @Transactional annotation to a method in which all SQL is executed in one transaction, with success or failure.

When you implement the @Transactional annotation ona method, Spring generates a proxy object based on that class. This proxy object is used as a bean. When using a method of this proxy object, if the @Transactional annotation exists on that method, The agent logic sets the automatic commit of the transaction to false before executing the original business logic method. If the business logic method does not fail, the agent logic commits the transaction, and if the business logic method fails, the transaction is rolled back.

Of course, you can configure which transactions can be rolled back for exceptions using the rollbackFor attribute in the @Transactional annotation. Runtimeexceptions and Errors are rolled back by default.

The Spring transaction isolation level is the database isolation level: plus a default level

(1) Read uncommitted

(2) Read COMMITTED

Repeatable read (3) Repeatable read

(4) Serializable

Db configuration isolation level is Read Commited, and Spring configuration isolation level is Repeatable Read. Which isolation level is used? The Spring configuration prevails. If Spring sets an isolation level that the database does not support, the effect depends on the database.

Spring transaction propagation mechanism

When multiple transactional methods call each other, how does a transaction propagate between those methods

Method A is A transaction method, A call the method during the implementation of B, then the method B for transactions and B are different to the requirement of the transaction will affect method A transaction specific implementation, the method A transaction at the same time also have effect to the transaction execution method B, this influence what is defined by the two methods is determined by the type of transaction propagation.

REQUIRED(Spring’s default transaction propagation type) : Create a new transaction if there is none, and join it if there is one

SUPPORTS: If a transaction currently exists, it joins the current transaction. If there is no transaction, it executes in a non-transactional manner

MANDATORY: If a transaction exists, the current transaction is added. If the transaction does not exist, an exception is thrown.

REQUIRES_NEW: Creates a new transaction and suspends the current transaction if one exists.

NOT_SUPPORTED: Executed in a non-transactional manner and suspends the current transaction if one exists

NEVER: no transaction is used and an exception is thrown if the current transaction exists

NESTED: Execute in a NESTED transaction if the current transaction exists, as if otherwise REQUIRED (start a transaction)

REQUIRES_NEW

REQUIRES_NEW creates a new transaction that is unrelated to the original one, while NESTED transactions (called a child transaction) are started when a current transaction exists (called a parent transaction). In the NESTED case, when the parent transaction is rolled back, the child transaction is also rolled back, while in REQUIRES_NEW, the original transaction is rolled back without affecting the newly opened transaction.

And REQUIRED

In the case of REQUIRED, the called and the caller use the same transaction when a transaction exists. Therefore, when an exception occurs in the called, the transaction will be rolled back regardless of whether the caller catches the exception. In the case of NESTED, the caller can catch the exception. In this way, only the child transaction is rolled back, and the parent transaction is not affected.

When do Spring transactions fail?

The principle of Spring transactions is AOP, with aspect enhancement, so the root cause of failure is that AOP does not work! The common cases are as follows

This is not a proxy class, but the UserService object itself.

The solution is simple: make this a proxy class for UserService.

2. Methods are not public

Transactional can only be used with public methods, otherwise transactions will not fail. To use a non-public method, enable the AspectJ proxy mode.

The database does not support transactions

4. Not managed by Spring

5. If the exception is eaten, the transaction will not be rolled back (or the exception thrown is not defined, default is RuntimeException).

What is bean autowiring, and in what ways?

To enable autowire, simply define the “autowire” attribute in the XML configuration file.

<bean id="cutomer" class="com.xxx.xxx.Customer" autowire="" />
Copy the code

The Autowire attribute can be assembled in five ways:

(1) No – By default, automatic configuration is manually set through the “ref” attribute.

Manual assembly: Explicitly specifying attribute values in either value or ref is manual assembly. You need to wire the bean through the 'ref' attribute.Copy the code

(2)byName- Automatic assembly based on bean property names.

The property name of Cutomer is Person, and Spring automatically installs beans with bean ID person through setter methods. <bean id="cutomer" class="com.xxx.xxx.Cutomer" autowire="byName"/> <bean id="person" class="com.xxx.xxx.Person"/>Copy the code

(3)byType- Automatic assembly according to the type of bean.

The Cutomer property Person is of type Person, and Spirng will auto-assemble the Person type through setter methods. <bean id="cutomer" class="com.xxx.xxx.Cutomer" autowire="byType"/> <bean id="person" class="com.xxx.xxx.Person"/>Copy the code

(4)constructor- Similar to byType, but an argument applied to the constructor. If a bean has the same type as a constructor parameter, it is autowered; otherwise, an exception is caused.

The Cutomer constructor takes an argument of type person, Spirng will automatically assemble the Person type through a constructor <bean ID ="cutomer" class=" com.XXX.XXX. cutomer" Autowire =" Construtor "/> <bean ID =" Person" class="com.xxx.xxx.Person"/>Copy the code

(5) Autodetect – Automate assembly by constructor if there is a default constructor, otherwise byType is used.

If there is a default constructor, autowire via Constructor, otherwise autowire by byType.Copy the code

@autoWired Automatic assembly beans, which can be used on fields, setter methods, constructors.