Java development engineer interview questions (1)

1. Annotate the implementation of @Transactional transactions


insert image description here
It is achieved through reflection + dynamic proxy!

2. 4 isolation levels + 7 propagation behaviors of Spring transactions


insert image description here
Remember what happens to them (dirty reads, dummy reads, non-repeatable reads).

insert image description here
Most use required, remember the concept of required.

3. Three injection methods of IOC


The most commonly used set injection.

Constructor injection.

Namespace p or c injection.

See: https://blog.csdn.net/IT_Holmes/article/details/121818148

4. 5 notification types of aop


There are two forms of aop configuration files:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       ">

	<bean id="serviceTest" class="com.itholmes.service.UserserviceImpl"></bean>
	
	<bean id="abc" class="com.itholmes.abc"></bean>
	
	<aop:config>
		<aop:aspect ref="abc">
			<aop:pointcut id="aa" expression="execution(* com.itholmes.service.*.*(..))"/>
			<!--下面的method就是上面ref引用类的方法名。-->
			<aop:after method="after" pointcut-ref="aa"/>
			<aop:before method="before" pointcut-ref="aa"/>
			<aop:after-throwing method="afterThrowing"  pointcut-ref="aa" throwing="e"/> <!--throwing 表示异常处理的方法的参数名 (可以不再异常通知中声明异常对象)-->
			<aop:after-returning method="afterReturning" pointcut-ref="aa"/>
			<aop:around method="around" pointcut-ref="aa"/>
		</aop:aspect>
	</aop:config>
	
	
</beans>

aop annotation form:
insert image description here

package com.itholmes.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AdviceTest {
    
    

    @Pointcut("execution(* com.itholmes.service.*.*(..))")
    //这里的test()方法必须有,就像是一个名字一样的标识。
    public void pointcut(){
    
    

    }

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint){
    
    
        System.out.println(joinPoint.getSignature().getName() + "前置通知---");
    }

    //2. 正常返回
    @AfterReturning("pointcut()")
    public void doAfterSuccess(JoinPoint joinPoint){
    
    
        System.out.println(joinPoint.getSignature().getName() + "正常返回通知---");
    }

    //3. 异常返回(与正常返回是互斥关系)
    @AfterThrowing("pointcut()")
    public void doAfterError(JoinPoint joinPoint){
    
    
        System.out.println(joinPoint.getSignature().getName() + "异常通知---");
    }

    //4. 环绕
    @Around(value = "pointcut()", argNames = "pjp")
    public Object doAround(ProceedingJoinPoint pjp) {
    
    
        Object[] args = pjp.getArgs();
        Object result;
        try {
    
    
            // Before
            System.out.println(pjp.getSignature().getName() + "环绕前置通知---");
            result = pjp.proceed(args);
            // AfterReturning
            System.out.println(pjp.getSignature().getName() + "环绕返回通知---");
        }catch (Throwable e){
    
    
            // AfterThrowing
            // System.out.println(pjp.getSignature().getName() + "环绕异常通知---");
            throw new RuntimeException(e);
        }finally {
    
    
            // After
            //  System.out.println(pjp.getSignature().getName() + "环绕最终通知---");
        }
        return result;
    }

    //5. 后置通知(最终通知)
    @After("pointcut()")
    public void doAfter(JoinPoint joinPoint){
    
    
        System.out.println(joinPoint.getSignature().getName() + "后置,也就是最终通知---");
    }


}

Don't forget to add profile info:

<bean id="annotationPointCut" class="com.itholmes.config.AdviceTest"></bean>
<aop:aspectj-autoproxy proxy-target-class="false"/>

Understand that normal returns and exception returns are mutually exclusive.

Post (final) notification, which will be executed with or without exception.

5. The role of distributed locks


Distributed lock: https://www.modb.pro/db/246339

Distributed lock: https://blog.csdn.net/zhaisharap/article/details/122471322

When multiple users operate the same data, for example, a courier picks up the goods, and multiple couriers go to pick up a piece of goods, a distributed lock is needed at this time. Because they are not distributed in a system, the effect of distributed locks can be achieved through redis, zookeeper, etc.

6. The process of the browser initiating a request


  1. The browser sends the http protocol request.
  2. First, according to the URL domain name, go to the local hosts file to find out whether there is a mapped IP, if not, go to DNS domain name resolution to get the IP address.
  3. After that, according to the resolved IP address, the client will perform a tcp three-way handshake to establish a connection with the server.
  4. Once the connection is established, it starts sending requests to the server.
  5. The server responds to the browser.
  6. Finally, the four waves of tcp disconnect the connection.
    insert image description here

7. http protocol


The http protocol is stateless, that is, it has no memory capability for transaction processing. Just make two requests to the server, the server does not know that the two http requests are from the same browser.

Cookie is to solve the problem of http statelessness.


Long connection, short connection, no connection:

Connectionless: Limit processing to one request per connection. After the server processes the client's request and receives the client's response, it disconnects. In this way, transmission time can be saved.

Short connection: Short connection means that after a request and response, the connection is closed for a while, which can save resources.

Long connection: Since HTTP/1.1, long connection is used by default to maintain connection characteristics. Using the long-connected HTTP protocol, this line of code will be added to the response header:

Connection:keep-alive

The long connection and short connection of the HTTP protocol are essentially the long connection and short connection of the TCP protocol.


Several common request headers:

  • Referer: It is part of the HTTP request header. When the browser (or simulated browser behavior) sends a request to the web server, the header information contains Referer. For example, if I have a www.baidu.com link in www.google.com, then click on this www.baidu.com, and its header information will contain:
 Referer=http://www.google.com
  • content-type : Request parameter type.
  • content-length : The length of the request parameter.
  • user-agent: Record some local information, provide the identification of the browser type and version you are using, operating system and version, browser kernel, etc.
  • host : domain name address (or IP + port number)

8. Stateful beans and stateless beans


Five scopes of beans: singleton, prototype, request, session, gloabal session

Stateful session bean: Each user has its own unique instance. During the user's lifetime, the bean maintains the user's information, that is, "stateful";

Once the user dies (the call ends or the instance ends), the bean's lifetime also ends. i.e. each user initially gets an initial bean.

Stateless session bean: Once the bean is instantiated, it is added to the session pool and can be shared by each user. Even if the user dies, the lifetime of the bean is not necessarily over, it may still exist in the session pool for other users to call.

Since there is no specific user, the state of a user cannot be maintained, so it is called a stateless bean.
But a stateless session bean is not stateless, if it has its own properties (variables), then these variables will be affected by all users who call it, which must be noted in practical applications.

Every time the bean defined by the prototype is obtained through the Spring container, the container will create a new Bean instance, each bean instance has its own properties and state, and the singleton has only one object globally.

As a rule of thumb, use prototype scope for stateful beans and singleton scope for stateless beans.

9. options request (cross-domain preflight)


The OPTIONS method of HTTP is used to obtain the communication options supported by the destination resource. Clients can use the OPTIONS method for a specific URL, or for the entire site (by setting the URL to "*"). (In short, you can use the options request to sniff which request method a request supports in the corresponding server).

This is because in the case of cross-domain, it is actively initiated when the browser initiates a "complex request". The cross-domain sharing standard specification requires that for those HTTP request methods that may have side effects on server data (especially HTTP requests other than GET, or POST requests with certain MIME types), the browser must first use the OPTIONS method to initiate a preflight request (preflight request), so as to know whether the server allows the cross-domain request. The actual HTTP request is not initiated until the server confirms the permission.

10. 9 common request methods of http

HTTP1.0 defines three request methods: GET, POST, HEAD

HTTP1.1 defines six request methods: PUT, DELETE, PATCH, OPTIONS, CONNECT, TRACE

  1. get requests the information of the specified page and returns the entity body (idempotent)
  2. post submits data to the specified resource for processing requests, the data exists in the request body (non-idempotent)
  3. head is similar to get, but does not return specific content, used to get the header (idempotent)
  4. put completely replaces and updates the specified resource data, if not, adds it (idempotent)
  5. delete deletes the data of the specified resource (idempotent)
  6. The patch part updates the data of the specified resource (non-idempotent)
  7. options allows the client to view the server's supported http request methods
  8. connect is reserved for proxy servers that can change connections to pipes
  9. trace traces requests received by the server for testing or diagnostics

11. How to prove that the current object is a singleton


Print this to see if some addresses are the same.

12. How to resolve member variables under multithreading


For example: I like to design a small function to know how many times the current interface has been accessed, design a member variable in the controller layer, and achieve a counting effect through this member variable.

For multi-threading, there will definitely be problems with the above code logic, how to solve it?

  • Adding synchronization locks is synchronized, but the efficiency is low.
  • AtomicInteger ageAtic = new AtomicInteger(0); Call the getAndIncrement method or decrementAndGet. Essentially the optimistic locking used by atomicInteger is implemented.
AtomicInteger integer = new AtomicInteger(0);
int i = integer.getAndIncrement(); // +1 操作
int i1 = integer.decrementAndGet(); // -1 操作

insert image description here

  • For non-counting, optimistic locking can also be used to solve such problems.

Optimistic lock: There is a field version in the database. Before starting the business execution, the version is queried. After the business is executed, the update operation is performed according to the version (optimistic lock: SQL statement level version + 1 where version = #{version}.)

The modification of the SQL statement is lost, and it can also be handled with pessimistic locking (select ... for update).


For this kind of business to increase or decrease, it is easy to have ABA problems. ABA problem: from A to B, and then B programmed A. This ABA problem.

13. The role of the transient keyword


The member variables marked with the transient keyword do not participate in the serialization process. The transient keyword can only modify variables, but not methods and classes.
insert image description here

14. The difference between / and /* in servlet


See: https://www.jb51.net/article/216853.htm

15. Those places in the code / generally refer to


/The code refers to the following places:
insert image description here

Put the page under the web-inf, and you can access it safely through the servlet.

16. Nine built-in objects of jsp


insert image description here

17. SpringMVC container and Spring container


The springmvc container and the spring container are child-parent containers. Start to scan the springmvc container first, so it is best not to scan the service path in the springmvc.xml file.

Of course, the Spring.xml file needs to scan the implementation classes under the service layer, and then put it in the spring container to configure the enhanced transaction of mybatis.

The above is not absolute, if you put all the transaction integration into springmvc, it is also feasible.

18. Spring interceptor + unified exception handling


See: https://blog.csdn.net/IT_Holmes/article/details/123089091?spm=1001.2014.3001.5502

19. The lazy and hungry style of the singleton design pattern


Singleton pattern:

  • Constructors are private, properties are private.
  • Write a method that specifically gets the current object, no matter how many times you get it, it will always be an object.
package com.itholmes.config;

public class Singleton {
    
    

    private static Singleton singleton = new Singleton();

    private Singleton(){
    
    
    }

    //饿汉式
    public static Singleton getSingleton(){
    
    
        return singleton;
    }

}

package com.itholmes.config;

public class Singleton {
    
    

    private static Singleton singleton = null;

    private Singleton(){
    
    
    }

    //懒汉式
    public static Singleton getSingleton(){
    
    
        if (singleton == null){
    
    
            singleton = new Singleton();
        }
        return singleton;
    }

}

20. Factory Pattern


See: https://www.runoob.com/design-pattern/factory-pattern.html

21. Java's assert assertion


1. assert condition;
where condition is an expression that must be true. If the expression evaluates to true, the assertion is true and no action is taken.
If the expression is false, the assertion fails and an AssertionError object is thrown. This AssertionError inherits from the Error object,
and Error inherits from Throwable. Error is an error object side by side with Exception, which is usually used to express system-level operational errors.

2. assert condition: expr;
here condition is the same as above. The colon is followed by an expression, which is usually used for prompt information after assertion failure. To put it bluntly, it is a value passed to the AssertionError constructor. On failure, the value is converted to its corresponding string and displayed.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("start");
        assert true;
        System.out.println("go on");
        assert false:"stop";
        System.out.println("end");
    }
}

To observe the operation of the assertion, you need to open the assertion function of the system class. We can use the -esa parameter to open it and use the -dsa parameter to close it. The full names of -esa and -dsa are -enablesystemassertions and -disenablesystemassertions, and the full and abbreviated names have the same function.
insert image description here

22. Spring's Assert assertion tool class


Spring's Assert assertion tool class, usually used for data validity checking. Located under the org.springframework.util.Assert package, using Assert can make complex judgments easier.

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/IT_Holmes/article/details/125613082