Java interview questions related to 6-spring frame

Spring Bean in the life cycle

 

Before you can think about the explanation Servlet life cycle: instantiation, the initial init, receiving a request service, destroy destroy;

    Bean Spring context is similar, the following

    1, an example of a Bean-- that is, we often say that the new;

    2. The context of the instantiated Spring Bean configuration - i.e. IOC injection;

    3, if the Bean has been achieved BeanNameAware interface calls setBeanName its implementation (String) method, passing here is the Spring configuration file id value of Bean

    4, if the Bean has been achieved BeanFactoryAware interface calls setBeanFactory its implementation (setBeanFactory (BeanFactory) passed a Spring plant itself (you can use this method to obtain additional Bean, simply configure the Spring configuration file in a plain Bean can);

    5, if the Bean has been achieved ApplicationContextAware interface calls setApplicationContext (ApplicationContext) method, passing in the Spring context (same content can also be achieved in this way, step 4, but better than 4, because ApplicationContext is a subinterface of BeanFactory, there more of implementation);

    6, if the Bean associated with the BeanPostProcessor interface will be called postProcessBeforeInitialization (Object obj, String s) method, often used as a change BeanPostProcessor Bean content and because of this is that at the end of the method call Bean initialization, you can It is applied to memory or cache technologies;

    7, if configured Bean init-method property in the Spring configuration file will automatically call the initialize method of its configuration.

    8, if the Bean associated with the BeanPostProcessor interface will be called postProcessAfterInitialization (Object obj, String s) method;

    Note: After completion of the above can be applied to this Bean, that the Bean is a Singleton, so under normal circumstances we call the same id of Bean will be the same instance in the content address, of course, can also be configured in the Spring configuration file non-Singleton, we do not repeat them here.

    9, when Bean is no longer needed, it will clean-up stage, if the Bean implements this interface DisposableBean, its implementation will call the destroy () method;

    10. Finally, if the Bean in Spring configuration to configure the destroy-method attributes, its configuration will automatically destroy method is called.

 

image.png

 

 

 

How to spring to resolve circular dependencies

Spring called circular dependency, refers to a scenario in which:

 

When we inject an object A, the object A need to inject some properties marked notes of these attributes is dependent on the object A, the object A are dependent initialization is complete, the object A is considered to create success. So, if the object A has a property that the object B, and object B has attributes that object A, then the objects A and B even circular dependencies, if not addressed, there will be: to create an object A -> a dependence treatment of B -> create Object B -> a B of the processing target -> create Object a -> a treatment depend on the B -> B ...... create objects such infinite cycle continues

 

Although you want to initialize a Bean, Bean must be injected in dependence considered successful initialization, but is not required at this time dependencies of dependencies are also injected into the success, as long as the dependent object constructor execution is over, even if the dependent objects exist, injection even if successful, as dependencies of dependencies, later also had time to initialize.

 

Thus, when we initialize a Bean, Bean first call the constructor of the object exists (the object which has not been injected dependency), then the object saved in memory when the generation cycle dependent, directly get saved before the object, so the cycle of dependence was terminated, it will depend on the successful completion of the injection.

 

for example:

A virtual target object has attributes B, the object B is also a property of the object A, i.e., A and B are cyclic dependency.
A create objects, call the constructor of A, and the preservation A. Then prepare to inject the dependent object A, found objects A dependent object B, then began to create the object B. Call the constructor of B, and the preserved B. Then prepare injected into the formation of B, find B dependent objects A, A before the object has been created, direct access to A and B to A is injected (note that at this time the object A has not been fully successful implantation, object A object B has not injected ), then B is created successfully. To create a successful injection of B A, then A also created a success. So circular dependency was resolved.

Note that, as the cycle-dependent manner for initialization mode can not solve the constructor

 

spring dependency injection, which has several ways

 

Spring is the main use of dependency injection. In general, injection dependency can be divided into three ways.

  • constructor injection.

  • setter injection.

  • interface injection.

  

Constructor injection

  Constructor implemented method of injection depends on the configuration, the method may be configured to have either no parameters parameters. In most cases, we are all created by the class constructor class object, Spring reflection of the way can also be used to complete the construction by using the injection method, which is the principle of constructor injection

 

public class Role {
 private Long id;  private String roleName;  private String note;    public Role(String roleName, String note) {  this.roleName = roleName;  this.note = note;  }   /******** setter and getter *******/ }

 

This time is no way to take advantage of no-argument constructor to create an object, in order to be able to create the object Spring correctly, you can do so like Listing.

 

<bean id="role1" class="com.ssm.chapter9.pojo.Role">
 <constructor-arg index="0" value="总经理"/>  <constructor-arg index="1" value="公司管理者"/> </bean>

 

constructorarg element argument constructor for the class definition, which is used to define the parameters of the position index, and the value is a set value, defined by such a method of using the constructor will know Spring Such Role (String, String) to create the objects. Such injection is relatively simple, but the disadvantages are also obvious, because the parameters here is relatively small, so readability is good, but if the argument a lot, so this construction method is more complicated, and this time should be considered setter injection

 

Use setter injection

 

Spring setter injection is the most mainstream injection method, which uses JavaBean specification defined setter methods to complete the injection, flexible and high readability. It eliminates the possibility of multiple parameters when using constructor injection, the first constructor can be declared with no parameters, then use setter injection to set the corresponding value, in fact, be the reality reflected by Java technology. It is assumed here for the first class code listing Role added a constructor with no parameters, and then do the configuration code list.

<bean id="role2" class="com.ssm.chapter9.pojo.Role">
 <property name="roleName" value="高级工程师"/>  <property name="note" value="重要人员"/> </bean

 

  Such Spring constructor will not generate the object parameters invoked by reflection while injecting reflection value configured by the corresponding setter. This approach is the most major way Spring, widely used in the practical work.

 

Interface injection

  There are times when resources are not from their own system, but from the outside world, such as database connection resources can be fully configured in under Tomcat, and then go get it through JNDI form, so that the database connection resources are resources that belong to foreign development project, this time we the interface injection may be employed to obtain it in the form of

 

Struts SpringMVC process or processing the request

  • The user sends a request to the front-end controller DispatcherServlet
  • DispatcherServlet receives a request to call HandlerMapping processor mapper.
  • The processor finds a specific mapping processor according to the request url, the object generation processor and a processor blocker (if any is generated) together back to DispatcherServlet.
  • DispatcherServlet by HandlerAdapter call processor processor adapter
  • Execution processor (Controller, also known as back-end).
  •  Controller to perform complete return ModelAndView
  •  HandlerAdapter the controller to return the results ModelAndView DispatcherServlet
  •  The DispatcherServlet ModelAndView pass  ViewReslover view resolver (
  • But if coupled with @Responsebody notes, the return value is not by viewResolver, but directly returned Object )
  •  After ViewReslover parse the returned concrete View
  •  View DispatcherServlet to render the view (the upcoming model data to fill view).
  •  User response DispatcherServlet

 

 

Spring AOP to solve the problem

 

AOP (Aspect Oriented Programming) is cut based programming, the non-invasive can add custom code in the original section layer functions, generally used for collecting logs certification authority scenes.

 

  • Jointpoint (connection points): a particular section little abstraction, may be on a field, a method, Spring is a specific form of PointCut (entry point), acts only on the method.
  • The Advice (notification): the specific operation performed at the connection point, how the enhancement process, into the front, rear, abnormal, finally, around the five cases.
  • Audience: the object is subjected to enhancement processing AOP frame, also called the enhanced object.
  • AOP proxy: Object created by the AOP framework, simply, is to strengthen the agent on the target object. In Spring AOP proxy will be a JDK dynamic proxy, the proxy may be CGLIB.
  • Weaving (weaving): The enhancement processing is added to the target object, creating a process object is enhanced

jdk dynamic proxy and proxy cglib similarities and differences

 

In Spring AOP proxy will be a JDK dynamic proxy, the proxy may be CGLIB

 

JDK dynamic proxy:

  • Interface to create your own call processor by implementing InvocationHandlet;
  • To create a dynamic proxy ClassLoader by specifying a set of interface objects and for the Proxy class;
  • Obtaining dynamic proxy class constructor by reflection, which is the only parameter type call processor interface type;
  • By creating dynamic proxy class instance constructor object configured to call the handler as a parameter into the parameter;

JDK dynamic proxy is a proxy for the interface mode, if the proxy is not the interface that the target can not do anything Spring, Spring production of new anonymous proxy class that implements the interface through the Java reflection mechanism, which rewrote the enhancement of AOP.

CGLib dynamic proxy:

CGLib is a powerful, high-performance production Code libraries, can achieve dynamic expansion java runtime class, Spring succession during the run to be a dynamic proxy class by CGlib, the parent class rewritten to achieve AOP Aspect Oriented Programming with it.

Comparison between the two:

  • JDK dynamic proxy is an interface-oriented.
  • CGLib dynamic proxy is achieved (if the proxy class is modified by the final keyword, so sorry fail) bytecode underlying proxy class to inherit
  • When the official introduction of the dynamic proxy object CGLib create high performance JDK dynamic proxies in the actual running time than a lot, but require additional dependencies
  • Spirng default to JDK dynamic proxy implementation mechanism

Caution:

  • If you want to be a proxy object is an implementation class, then Spring will use JDK dynamic proxy to complete the operation
  • If you want to be a proxy object is not a class that implements it, Spring will be forced to use dynamic proxy CGLib

 

 

In Spring BeanFactory and FactoryBean What is the difference

Common:

         Are interfaces

the difference:

BeanFactory, ending Factory, indicating that it is a factory class (Interface), which is responsible for the production and management of a factory bean. In Spring, the core of the interface is the BeanFactory IOC containers, Its responsibilities include: instantiating or configuration application objects and the dependencies between those objects. BeanFactory only interfaces, not the specific realization IOC containers, but Spring container gives many implementations, such as DefaultListableBeanFactory, XmlBeanFactory, ApplicationContext the like, which is commonly used in a XmlBeanFactory, to achieve the objects described in XML and application It dependencies between objects.

      The FactoryBean, under normal circumstances, Spring specify a class instance of Bean, in some cases, Bean instantiation process is complex, if, it is necessary to provide a large amount of configuration information in a conventional manner by use of the class attribute reflection. Flexibility of arrangement is limited, when the coding method employed may get a simple solution. Spring aims to provide a plant org.springframework.bean.factory.FactoryBean class interface, the user can instantiation logic implementing this interface by Bean

 

What IOC Spring framework is the principle

 

(1) .IoC is Inversion of Control acronym, some translated as "inversion of control", also translated into "reverse-control" or "control upside down."

(2). In 1996, Michael Mattson in articles that explore object-oriented framework of one, first proposed the concept of IoC. It is simply to decompose complex systems into objects of mutual cooperation through the package after these object classes, the internal implementation is transparent to the outside, thereby reducing the complexity of the problem, and can be reused and flexibly expanded. IoC view generally proposed theory is this: by means of a "third party" decoupling between objects with dependencies, as shown below:

That is, after the respective object class packaging, to classes associated with these objects through IoC container. To be contacted via IoC container between such objects and objects, but there is no direct link between the subject and the object.

If the system is removed after IoC container object A and object B have a direct relationship, as shown below:

 

 

Spring transaction propagation properties

 

Transaction propagation behavior (propagation behavior) refers to a transaction when the transaction method calls another method, this method should be how to make the transaction. 

For example: methodA transaction method is invoked methodB transaction method, methodB is to continue to run the affairs of the caller methodA it, or start a new run their own affairs, which is determined by the propagation behavior methodB transactions.

 

Spring defines seven communication behavior:

 

 

How to implement database transaction Spring

 

Programmatic transaction: allows the user to precisely define the boundary of the transaction code. rarely use

 

Declarative transaction: (based on AOP) helps the user to decouple the operating and business rules. Simply put, programmatic transaction intrude into the business code inside, but provides a more detailed transaction management; and declarative transaction because the AOP-based, so both play a role in the management of affairs, but also does not affect the concrete realization of business code.

 

Declarative transaction management @Transactional only need to use annotations and @EnableTransactionManagement (open transaction management function). It is based on Spring AOP implementation and realization through annotations, simple to implement, is not invasive to the original code.

 

@Transactional annotation centralized situation does not work:

When ①Transactional comment tagging method modifier non-public, @ Transactional annotation will not work.

② call the class method calls inside @Transactional mark within the class. In this case the transaction would not lead to open.

Internal affairs ③ method to capture the exception, not throw new Exception, the operation will not cause the transaction to be rolled back.

④ abnormal type is not unchecked exception. I want to check if an exception would also like to roll back how to do, annotations above stated exception type can be. @Transactional (rollbackFor = Exception.class)

 

 

How Spring IoC AOP own realization in code

 

The difference between Hibernate and ORM frameworks such Ibatis? What is ORM, what is solving pain points

 

Hibernate use of the twelve cache, Lazy-Load understanding

 
 
 

Guess you like

Origin www.cnblogs.com/reload-sun/p/12216745.html