Java--Spring

1. Talk about your understanding of spring IOC and DI , what is the difference between them?

The concept of IoC Inverse of Control is to hand over the control of the UserService object that was originally created manually in the program to the Spring framework. In short, the control of the UserService object created is inverted to the Spring framework

DI: Dependency Injection Dependency injection, when the Spring framework is responsible for creating a Bean object, dynamically injects the dependent object into the Bean component 

Interview Question: What is the difference between IoC and DI? 

IoC Inversion of Control, refers to the inversion of object creation rights to the Spring container, DI Dependency Injection, refers to the process of Spring object creation, the object dependency properties are injected through configuration 

2. What is the difference between the BeanFactory  interface and  the ApplicationContext  interface?

    ①ApplicationContext interface inherits BeanFactory interface, Spring core factory is BeanFactory, BeanFactory adopts lazy loading, Bean will be initialized when gettingBean for the first time, ApplicationContext will initialize Bean when loading configuration file.

    ②ApplicationContext is an extension to BeanFactory, which can perform internationalization processing, event delivery and bean autowiring, as well as Context implementation of various application layers 

ApplicationContext is basically used in development, web projects use WebApplicationContext, and BeanFactory is rarely used 

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
IHelloService helloService = (IHelloService) beanFactory.getBean("helloService");
helloService.sayHello();

 

3. What are the ways of spring configuration bean instantiation?

1) Instantiate using the class constructor (no parameters by default)

<bean id="bean1" class="cn.itcast.spring.b_instance.Bean1"></bean>

2) Instantiate using a static factory method (simple factory pattern)

// The meaning of the following configuration: call the getBean2 method of Bean2Factory to get bean2 
<bean id="bean2" class ="cn.itcast.spring.b_instance.Bean2Factory" factory-method="getBean2"></bean>

  3) Instantiate using an instance factory method (factory method pattern )

// First create the factory instance bean3Facory, and then create the target bean instance through the factory instance 
<bean id="bean3Factory" class ="cn.itcast.spring.b_instance.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>

 

4. Briefly talk about the life cycle of spring ?

    1) In the configuration <bean> element, specify the Bean initialization method through init-method, and specify the Bean destruction method through destroy-method 

<bean id="lifeCycleBean" class="cn.itcast.spring.d_lifecycle.LifeCycleBean" init-method="setup" destroy-method="teardown"></bean> 

 

Issues to be aware of:

    * destroy-method is only valid for scope="singleton"  

    * Destruction method, the ApplicationContext object must be closed (manually called) before it will be called

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
applicationContext.close();

 

2) The complete life cycle of Bean (11 steps) [understand the content, but it will help to understand the internal operation of spring]

① instantiate bean object instantiation

②populate properties package properties

③ If the Bean implements BeanNameAware, execute setBeanName

④ If the Bean implements BeanFactoryAware or ApplicationContextAware, set the factory setBeanFactory or the context object setApplicationContext

⑤ If there is a class that implements BeanPostProcessor (post-processing Bean), execute postProcessBeforeInitialization, and the BeanPostProcessor interface provides hook functions to dynamically expand and modify the Bean. (The program automatically calls the post-processing Bean)

public class MyBeanPostProcessor implements BeanPostProcessor {
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println( "Step 8: Post-processing Bean, after initialization." );
         // Post-processing Bean, add a dynamic proxy here, and modify the Bean. 
        return bean; // Return the bean, indicating that it has not been modified. If a dynamic proxy is used and the proxy object is returned, then it is modified. 
    }
     public Object postProcessBeforeInitialization(Object bean, String beanName)
             throws BeansException {
        System.out.println( "Step 5: Post-processing Bean: before initialization!!" );
         // Post-processing Bean, add a dynamic proxy here, and modify the Bean. 
        return bean; // Return the bean itself, indicating no modification. 
    }
}
Note: This pre-processing bean and post-processing bean will intercept all beans.

⑥ If the Bean implements InitializingBean, execute afterPropertiesSet 

⑦Call <bean init-method="init"> to specify the initialization method init

⑧ If there is a class implementing BeanPostProcessor (processing Bean), execute postProcessAfterInitialization

⑨ Execute business processing

⑩ If the Bean implements DisposableBean, execute destroy

⑪Call <bean destroy-method="customerDestroy"> to specify the destruction method customerDestroy

 

5. Please introduce the life cycle and scope  of beans in the Spring framework

(1) bean definition

    Use <bean></bean> in the configuration file to define it.

(2) bean initialization

    There are two ways to initialize:

A. It is done by specifying the init-method attribute in the configuration file

B. Implement the org.springframwork.beans.factory.InitializingBean interface

(3) bean call

    There are three ways to get a bean instance and call it

(4) bean destruction

    There are two ways to destroy

A. Use the destroy-method property specified in the configuration file

B. Implement the org.springframwork.bean.factory.DisposeableBean interface

##Scope

singleton

When a bean is scoped to singleton, there will only be one shared bean instance in the Spring IoC container, and all requests for the bean will only return the same instance of the bean as long as the id matches the bean definition.

prototype

A prototype-scoped bean causes a new bean instance to be created each time the bean is requested (either by injecting it into another bean, or by calling the container's getBean() method programmatically). As a rule of thumb, you should use prototype scope for all stateful beans and singleton scope for stateless beans

request

In an HTTP request, a bean definition corresponds to an instance; that is, each HTTP request will have its own bean instance, which is created according to a bean definition. This scope is only valid in the context of a web-based Spring ApplicationContext.

session

In an HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the context of a web-based Spring ApplicationContext.

global session

In a global HTTP Session, a bean definition corresponds to an instance. Typically, this only works when using the portlet context. This scope is only valid in the context of a web-based Spring ApplicationContext.

 

6. What are the ways of Bean injection properties?

Spring supports constructor injection and setter method injection

    Constructor injection, which is done through the <constructor-arg> element

    The setter method is injected, and the injection is completed through the <property> element [commonly used in development]

 

7. What is AOP and what is the role of AOP ?

Aspect-Oriented Programming (AOP) provides another way of thinking about program structure, and in this way makes up for the deficiencies of Object-Oriented Programming (OOP). In addition to classes, AOP provides aspects. Aspects modularize concerns, such as transaction management across multiple types and objects 

A key component of Spring is the AOP framework, which allows you to choose whether to use AOP to provide declarative enterprise services, especially to replace EJB declarative services. The most important service is declarative transaction management, which builds on Spring's abstract transaction management. Allows users to implement custom aspects and use AOP to improve the use of OOP. Spring AOP can be regarded as an enhancement to Spring 

 

 

8. What are the core classes of Spring and what are the functions of each?

BeanFactory: Generate a new instance, which can implement the singleton pattern

BeanWrapper: Provides unified get and set methods

ApplicationContext: Provides the implementation of the framework, including all the functions of BeanFactory

 

9. How to configure 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>abc</value></property>
<property name=”password”><value>abc</value></property>
</bean>

 

 

10. Can the applicationContext.xml file in Spring be changed to another file name? 

ContextLoaderListener is a ServletContextListener that is initialized when your web application starts. By default, it looks for Spring's configuration in the WEB-INF/applicationContext.xml file. You can change the location of the Spring configuration file by defining a <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>

 

11. How to define hibernate mapping in Spring

Add the hibernate mapping file to the applicationContext.xml file in the web/WEB-INF directory.

example:

<property name=”mappingResources”>
<list>
<value>org/appfuse/model/User.hbm.xml</value>
</list>
</property>

 

12. How does Spring handle thread concurrency?

Spring uses ThreadLocal to solve thread safety problems

We know that in general, only stateless beans can be shared in a multi-threaded environment. In Spring, most beans can be declared as singleton scope. It is because Spring uses ThreadLocal to process non-thread-safe states in some beans (such as RequestContextHolder, TransactionSynchronizationManager, LocaleContextHolder, etc.), making them thread-safe, because stateful beans can be shared among multiple threads.

Both ThreadLocal and thread synchronization mechanisms are designed to solve the access conflict problem of the same variable in multiple threads.

In the synchronization mechanism, the lock mechanism of the object ensures that only one thread accesses the variable at the same time. At this time, the variable is shared by multiple threads. Using the synchronization mechanism requires the program to carefully analyze when to read and write the variable, when to lock an object, and when to release the object lock and other complicated issues. Program design and writing relatively difficult.

ThreadLocal solves the concurrent access of multiple threads from another perspective. ThreadLocal will provide each thread with an independent copy of the variable, thereby isolating the access conflict of multiple threads to the data. Since each thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe shared objects. When writing multi-threaded code, unsafe variables can be encapsulated into ThreadLocal.

Since any type of object can be held in ThreadLocal, the get() provided by the lower version of JDK returns an Object object, which requires type conversion. But JDK5.0 solves this problem well through generics, which simplifies the use of ThreadLocal to a certain extent.

To sum up, for the problem of multi-threaded resource sharing, the synchronization mechanism adopts the method of "exchanging time for space", while ThreadLocal adopts the method of "exchanging space for time". The former only provides a variable for different threads to queue for access, while the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

 

13. Why have things spread behavior?

 

14. Introduce Spring 's transaction management

    A transaction is a unified commit or rollback operation for a series of database operations (such as inserting multiple pieces of data). This prevents dirty data and prevents problems with database data.

In order to avoid this situation in development, transaction management is generally performed. Spring also has its own transaction management mechanism, which is generally managed by TransactionMananger. This function can be accomplished through Spring injection. Spring provides several classes for transaction processing:

TransactionDefinition //Transaction attribute definition

TranscationStatus //Represents the current transaction, which can be committed and rolled back.

PlatformTransactionManager is the basic interface provided by spring for managing transactions. There is an abstract class that implements AbstractPlatformTransactionManager. The transaction management classes we use, such as DataSourceTransactionManager, are all subclasses of this class.

General Transaction Definition Steps:

TransactionDefinition td = new TransactionDefinition();
TransactionStatus ts = transactionManager.getTransaction(td); 
try{ 
//do sth
transactionManager.commit(ts);
}catch(Exception e){
transactionManager.rollback(ts);
}

 

 

The transaction management provided by spring can be divided into two categories: programmatic and declarative. Programmatic is more flexible, but the amount of code is large, and there are more repeated codes; declarative is more flexible than programmatic.

Programmatically mainly use transactionTemplate. Some commits, rollbacks, and a series of transaction object definitions are omitted, and transaction management objects need to be injected.

void add(){
transactionTemplate.execute( new TransactionCallback(){ 
pulic Object doInTransaction(TransactionStatus ts){
//do sth
}
}
}

 

Declarative:

使用TransactionProxyFactoryBean:PROPAGATION_REQUIRED PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly

Dynamic proxy around Poxy that automatically commits and rolls back transactions

org.springframework.transaction.interceptor.TransactionProxyFactoryBean

PROPAGATION_REQUIRED – supports the current transaction, if there is no current transaction, create a new transaction. This is the most common choice.
PROPAGATION_SUPPORTS – Support current transaction, if there is no current transaction, execute in non-transactional mode.
PROPAGATION_MANDATORY – supports the current transaction, throws an exception if there is no current transaction.
PROPAGATION_REQUIRES_NEW – create a new transaction, if there is a current transaction, suspend the current transaction.
PROPAGATION_NOT_SUPPORTED - Performs the operation in a non-transactional manner, suspending the current transaction if there is one.
PROPAGATION_NEVER – Execute non-transactionally, throw an exception if there is currently a transaction.
PROPAGATION_NESTED – If a transaction currently exists, execute within a nested transaction. If there are no current transactions, do something similar to PROPAGATION_REQUIRED.

 

15. Explain some terms in Spring AOP

Aspect: A modularity of concerns that may cut across multiple objects. Transaction management is a good example of cross-cutting concerns in J2EE applications. In Spring AOP, aspects can be implemented using generic classes (schema-based style) or with @Aspect annotations (@AspectJ style) in ordinary classes.

Joinpoint: A specific point during program execution, such as when a method is called or when an exception is handled. In Spring AOP, a join point always represents the execution of a method. By declaring a parameter of type org.aspectj.lang.JoinPoint, the body part of the Advice can obtain the join point information.

Advice: An action performed at a particular Joinpoint of an aspect. There are various types of notifications, including "around", "before", and "after". Types of notifications are discussed in a later section. Many AOP frameworks, including Spring, use interceptors as their advice model and maintain a joinpoint-centric chain of interceptors.

Pointcut: An assertion that matches a Joinpoint. Advice is associated with a pointcut expression and runs on join points that satisfy this pointcut (for example, when a method of a particular name is executed). How a pointcut expression matches a join point is at the heart of AOP: Spring uses the AspectJ pointcut 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 proxied object. For example, you can use an import to make the bean implement the IsModified interface in order to simplify the caching mechanism.

Target Object: An object advised by one or more aspects. Some people call it an advised object. Since Spring AOP is implemented through runtime proxies, this object is always a proxied object.

AOP Proxy (AOP Proxy): An object created by the AOP framework to implement the aspect contract (including functions such as informing method execution). In Spring, AOP proxies can be JDK dynamic proxies or CGLIB proxies. Note: With the newly introduced schema-based style and @AspectJ annotation style aspect declarations in Spring 2.0, proxy creation is transparent to users of these styles.

Weaving: Connect aspects to other application types or objects and create an advised object. These can be done at compile time (e.g. with the AspectJ compiler), class loading time and runtime. Spring, like other pure Java AOP frameworks, does weaving at runtime.

 

 

16. What types of notifications are there?

Before advice: An advice that executes before a join point, but which cannot prevent execution before the join point (unless it throws an exception).

After returning advice: Advice that executes after a join point completes normally: for example, a method returns normally without throwing any exceptions.
After throwing advice: Advice that is executed when a method exits with an exception thrown.
After (finally) advice: Advice that is executed when a join point exits (whether it is a normal return or an abnormal exit).
Around Advice: Advice that surrounds a join point, such as a method call. This is the most powerful type of notification. Surround advice can be used to accomplish custom behavior before and after method calls. It also chooses whether to continue execution of the join point or simply return their own return value or throw an exception to end execution.
 
Wraparound notifications are the most commonly used type of notification. Most interception-based AOP frameworks, such as Nanning and JBoss4, only provide wraparound advice.
The concept of pointcut and join point matching is the key to AOP, which makes AOP different from other older technologies that only provided interception functionality. Pointcuts allow positioning advice (advice) to be independent of the OO level. For example, an around advice that provides declarative transaction management can be applied to a set of methods across multiple objects (such as all business operations in the service layer).

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782614&siteId=291194637