Spring interview questions

Prodigal son Tang Shao 2022-02-13 07:29:30 阅读数:639

spring interview questions

spring Interview questions

1.Spring At the heart of ?

answer : Inversion of control (IoC) And face the facet (AOP)

2. What is? IOC?

answer :

1. Leave the creation of objects to the external container , The program only needs to receive and obtain the object . Such as class A To call a class B Methods , We used to be in class A in , By itself new One class B, Then call the class B Methods , Now let's new class B Leave it to spring To do it , Use java The reflection mechanism of , Create objects and manage objects dynamically at run time according to the configuration file , And call the object's methods .

3.spring Common injection methods

answer :

There are three common injection methods : Constructor injection ,setter Inject , Annotation based injection

1. Constructor injection

Write parameter construction methods in class , stay xml In the configuration corresponding to bean The constructor parameters of

2.setter Inject

Class set Method , stay xml Configuration correspondence bean Method parameters of

3. Annotation based injection

Use @Resource,@Autowired Do dependency injection

4. What is? AOP?

answer :

AOP It is mainly used to integrate those irrelevant to the business , But the public behavior and logic that affect multiple objects , Extract and package as a reusable module , This module is named “ section ”(Aspect), Can be used for logging 、 Transactions, etc . For example, do log facet class , Facet class of transaction .

How to make a faceted class ?

1. Use @Aspect The annotation will be a java Class is defined as a tangent class
2. Use @Pointcut Define an entry point , It can be a regular expression
3. Cut in content at different positions of the cut in point according to needs , It is based on aop Type of notification .

such as :

【 Pre notice 】 Execute... Before executing the target object method
【 The rear notice 】 Execute... After executing the target object method , Do not execute in case of exception .
【 Abnormal notice 】 Execute the target object method only when there is an exception
【 Final notice 】 Execute... After executing the target object method , Always carry out
【 Surrounding the notification 】 Around the target method execution ( Equivalent to a combination of the previous four notifications )

​ Use @Before Cut into the content at the beginning of the entry point
​ Use @After Cut into the content at the end of the pointcut
​ Use @AfterReturning At the entry point return Cut into the content after the content ( It can be used to process the returned value )
​ Use @Around Cut into the content before and after the entry point , And control when to execute the content of the pointcut itself
​ Use @AfterThrowing It is used to handle the processing logic after the exception is thrown in the cut in content part

import java.util.Arrays;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* Project log section
* 2019 year 1 month 5 Japan
*/
@Aspect
@Component
public class WebLogAspect {
private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
private static final String PLATFORM_NAME = "xxx Project name ";
/**
* Count the time
*/
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.web.controller..*.*(..))")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// Received request , Record the request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// Print request parameters
Map<String, String[]> paramMap = request.getParameterMap();
if(paramMap != null && paramMap.size() > 0) {
StringBuffer paramSbf = new StringBuffer();
for(String mapKey:paramMap.keySet()) {
String[] mapValue = paramMap.get(mapKey);
// Add judgement
if(mapValue != null && mapValue.length > 0) {
for(String paramStr:mapValue) {
if(StringUtils.isNotBlank(paramStr)) {
paramSbf.append(" Parameters "+mapKey+"=");
paramSbf.append(paramStr);
paramSbf.append(";");
}
}
}//END if
}//END for
// Print log parameters
logger.info(PLATFORM_NAME+"-->request Request parameters PARAM : " + paramSbf);
}//END if
// Record the request
logger.info(PLATFORM_NAME+"-->request request URL : " + request.getRequestURL().toString());
logger.info(PLATFORM_NAME+"-->request Request method HTTP_METHOD : " + request.getMethod());
logger.info(PLATFORM_NAME+"-->request Request method IP : " + getIP(request));
logger.info(PLATFORM_NAME+"-->request Request class method CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info(PLATFORM_NAME+"-->request request ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// Processing requests , Return content
logger.info(PLATFORM_NAME+"-->response Request response result RESULT: " + ret);
logger.info(PLATFORM_NAME+"-->response Request response time = 【" + (System.currentTimeMillis() - startTime.get())+"】 millisecond ");
}
/**
*
* @param request
* @return
*/
private static String getIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}

5.spring Support several kinds of bean Scope of action ?

singleton( The singleton pattern ):bean At every spring ioc There is only one instance in the container

prototype( Archetypal model ): One bean The definition of can have multiple instances

request: Every time http Request will create a bean, This scope is only based on web Of SpringApplicationContext In the case of

session: stay Http Session in , One bean Definition corresponds to an instance , This scope is only based on web Of SpringApplication In the case of

global-session( The global session ): In a global HTTP Session in , One bean Definition corresponds to an instance

6.spring Business

spring Transactions include declarative transactions and programmatic transactions

7. How to do spring Declarative transactions

xml The way

1. Configure transaction manager

2. Configure transaction notification rules

3.Aop To configure (Aop To configure = Pointcut expression + Transaction notification rules )

Annotation mode

1. Configure transaction manager

2. Transaction annotations support

3. Methodically used @Transactional

springboot The way

1. Using annotations @EnableTransactionManagement After enabling transaction support

2. Methodically used @Transactional

8.spring Communication affairs

1.PROPAGATION_REQUIRED( Default transaction propagation behavior )

meaning : Indicates that the current method must be running in a transaction . If the current transaction exists , Method will run in the transaction , otherwise , Will start a new transaction .

For example, there are two ways :

@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {
methodB();
// do something
}
@Transactional(propagation = Propagation.REQUIRED)
public void methodB() {
// do something
}

Call alone methodB When the method is used , Because there is no transaction in the current context , So it opens a new transaction .
call methodA When the method is used , Because there is no transaction in the current context , So it opens a new transaction . When executed methodB when ,methodB Transaction found in current context , So join the current transaction .

2.PROPAGATION_SUPPORTS

meaning : If a transaction exists , Support current transaction . If there is no transaction , It is not the execution of a transaction .

For example, there are two ways :

@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {
methodB();
// do something
}
// The transaction property is SUPPORTS
@Transactional(propagation = Propagation.SUPPORTS)
public void methodB() {
// do something
}

Simply call methodB when ,methodB Methods are non transactional . When calling methdA when ,methodB Then joined. methodA In the transaction of , To carry out affairs .

3.PROPAGATION_MANDATORY

meaning : If a transaction already exists , Support current transaction . If there is no active transaction , Throw an exception

@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {
methodB();
// do something
}
// The transaction property is MANDATORY
@Transactional(propagation = Propagation.MANDATORY)
public void methodB() {
// do something
}

When calling alone methodB when , Because there is currently no active transaction , An exception will be thrown throw new IllegalTransactionStateException(“Transaction propagation ‘mandatory’ but no existing transaction found”); When calling methodA when ,methodB Then add to methodA In the transaction of , To carry out affairs

4.PROPAGATION_REQUIRES_NEW

If a transaction already exists , Then suspend the existing transaction first , Start a new business by yourself , Finish your own business , Resume the suspended transaction

Example :

@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {
doSomeThingA();
methodB();
doSomeThingB();
// do something else
}
// The transaction property is REQUIRES_NEW
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodB() {
// do something
}

When calling

main{
methodA();
}

Equivalent to calling

main(){
TransactionManager tm = null;
try{
// To obtain a JTA Transaction manager
tm = getTransactionManager();
tm.begin();// Start a new business
Transaction ts1 = tm.getTransaction();
doSomeThing();
tm.suspend();// Suspend current transaction
try{
tm.begin();// Reopen the second transaction
Transaction ts2 = tm.getTransaction();
methodB();
ts2.commit();// Commit the second transaction
} Catch(RunTimeException ex) {
ts2.rollback();// Roll back the second transaction
} finally {
// Release resources
}
//methodB After the execution , Resume the first transaction
tm.resume(ts1);
doSomeThingB();
ts1.commit();// Commit the first transaction
} catch(RunTimeException ex) {
ts1.rollback();// Roll back the first transaction
} finally {
// Release resources
}
}

ad locum , I put ts1 It's called outer affairs ,ts2 It's called an inner transaction . As you can see from the code above ,ts2 And ts1 It's two separate things , Irrelevant .Ts2 Success does not depend on ts1. If methodA Method is calling methodB Methods after the doSomeThingB Method failed , and methodB The results of the method are still submitted . Besides methodB The results of other code are rolled back

5.PROPAGATION_NOT_SUPPORTED

Always execute... Non transactionally , And suspend any existing transactions

6.PROPAGATION_NEVER

Always execute... Non transactionally , If there is an active transaction , Throw an exception .

7.PROPAGATION_NESTED

If a transaction already exists , Then this method will run in nested transactions , The rollback of outer transaction can cause the rollback of inner transaction . The exception of inner transaction does not cause the rollback of outer transaction . If there is no transaction , Just follow PROPAGATION_REQUIRED equally .

copyright:author[Prodigal son Tang Shao],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130729282826.html