2013年12月10日星期二

When asked about the interview is how to control the affairs of the spring ? How do you answer ?

 This post last edited by defonds on 2013-11-05 14:37:37
several interviews have encountered such a problem , explain it out.

know how to use this framework spring , but ShuiBuLai its principles, ashamed.

brother sincerely ask for advice !
------ Solution ---------------------------------------- ----
spring affairs through " declarative transaction " approach to the management of affairs , that is declared in the configuration file , the transaction section cut through the AOP process . The biggest advantage is greatly reduced amount of code , such as:

Transaction tx=session.getTransaction();
session.beginTransaction();
tx.commit();
tx.rollback();

so kind to write code that is not duplicated in every way , simplifying procedures , improving work efficiency.
------ Solution ---------------------------------------- ----
1.IOC inversion of control : control over the object itself turned container , the container on the bean object control.
2.AOP Aspect Oriented Programming : the specific class to create a proxy class corresponding to the operation of specific classes through a proxy class .
spring is a container for objects to be managed through the spring of this container , according to the configuration file to achieve the spring administration of the object.
So understand it, so I can only answer temporarily , too deep and I do not know how to say
------ Solution -------------- ------------------------------
SPRING affairs of consistency

not read the source code
But regardless of AOP or IOC has transaction support

speculate about
SPRING is a large container , a large factory class
then when you get an object from the time SPRING
object when establishing
Turn on the transaction, and then the object to you, let you go to use
At the end of your method will return the object This time
commit the transaction and close the transaction

These operations are implemented within the framework of
so long as the use of SPRING will certainly be surrounded
firm ------ Solution ----------------------- ---------------------
matters is how to understand a concept , and how do write their own affairs

try {
/ / business logic
if ( success )
commit ();
} catch (e) {
/ / abnormal
rollback ();
}

spring will catch up to you throw the exception, and then help you try catch, catch the exception if found , would put the connection does not commit, rollback directly , so we have the time to configure declarative transaction What is an argument exception class , the default should be runtimexcepttion it ...
------ Solution ------------------------- -------------------
to see Java 's dynamic proxy to understand the principles of how the story .
------ Solution ---------------------------------------- ----
My suggestion is that, first of all answer the IOC and AOP, and then introduce these two simple things simple , do not need to say too much, but to achieve focus , then , a direct offer,
------ Solution ------------------------------------------ -
Spring AOP is achieved by means of transaction control , the specific implementation is by spring-asm.jar and cglib.jar, because both offer a jar with a dynamic proxy -related functions, the realization of the implant operation features of the new features . Similar functionality can be achieved through our hand , if the byte codes to grasp the concept better, you can take advantage of apache bcel library for more detailed function control .

above untrue unreliable interview bragging use only . The basic answer to the other side so you do not ask deep , in fact, people will not interview specific details .
------ Solution ---------------------------------------- ----
spring transaction configuration , there are two ways, one is configured transaction manager , and the other is to control the affairs of the code Transaction Manager configuration
way we often used are often used in the configuration file . Matters into jdbc templates and transaction management code controlled , jdbc default auto-commit , the transaction manager and we usually have the same commit rollback operation. Leisure time to look at the development of guidelines it
------ For reference only ---------------------------- -----------
AOP
------ For reference only ---------------------------------------
have P ashamed , using the framework / framework for understanding the principles / write framework is a level of something wrong.
------ For reference only -------------------------------------- -

makes sense , if the current take 4000 dollars a month , then you do not know how it was achieved. If I were the interviewer , I would like this question , I think you can know unexpected promise , but if you happen to know it is not very good yet
------ For reference only ----- ----------------------------------

makes sense , if the current take 4000 dollars month , then you do not know how it was achieved. If I were the interviewer , I would like this question , I think you can know unexpected promise , but if you happen to know it is not very good yet  

did so !
------ For reference only -------------------------------------- -

---- - For reference only ---------------------------------------
heartfelt thanks to more several answers ~ !
------ For reference only -------------------------------------- -
framework automatically give you manage affairs ! Really do not know what the specific realization !
------ For reference only ----------------------------- ----------
general I met this problem , I said , configured, automatically back to manage affairs , if he asked how to configure , I said someone configuration.
------ For reference only -------------------------------------- -
1 Floor positive solution, ponder about !
------ For reference only -------------------------------------- -
help the landlord from the top to let more people see
------ For reference only ------------------------ ---------------


very good!
------ For reference only ---------------------------- -----------
- according upstairs several answers , I combined the best answer ( dawned , thank you God )

Spring transaction , it can be said is an implementation of Spring AOP .

AOP Aspect Oriented Programming , ie without modifying the source code of the case , the original function can be extended to operate through a proxy class for a specific category .

spring is a container for objects to be managed through the spring of this container , according to the configuration file to achieve the spring administration of the object.
Transaction Statement
spring , there are two ways , programmatic and declarative . spring mainly through " declarative transaction " approach to the management of affairs , that is declared in the configuration file , the transaction section cut through the AOP process, the biggest benefit is greatly reducing the amount of code .


------ For reference only ---------------------------------- -----
top interview questions
------ For reference only ------------------------ ---------------
will be used and will be manufactured and constructed that there is not a level of , for example, you know that using a mobile phone call , the phone does not know how to achieve .
------ For reference only -------------------------------------- -
This is certainly the Runescape 3 Gold best advantage, whereby you can understand the strategic practice of a win-win game. Diablo 3 guides will help you to Old School Runescape Gold conquer the monsters in the game field, ;. whereby you can handle them with all ease
------ For reference only --------------------- ------------------
top, a very common interview questions
------ For reference only ---------- -----------------------------
 The adoption focus
------ For reference only --------------- ------------------------
lot of great God , worship , and I had not yet learned conjunction
------ For reference only ---------------------------------------
who can then talk about things AOP
------ For reference only -------------------------------------- -
think 26 F is a positive solution
------ For reference only ----------------------------- ----------
wait for points, you must give points
------ For reference only ------------------ ---------------------
top one, common interview mentioning Yeah
------ For reference only ---- -----------------------------------
Spring transaction , can be said to Spring an AOP implementation.

AOP Aspect Oriented Programming , ie without modifying the source code of the case , the original function can be extended to operate through a proxy class for a specific category .

spring is a container for objects to be managed through the spring of this container , according to the configuration file to achieve the spring administration of the object.
Transaction Statement
spring , there are two ways , programmatic and declarative . spring mainly through " declarative transaction " approach to the management of affairs , that is declared in the configuration file , the transaction section cut through the AOP process, the biggest benefit is greatly reducing the amount of code .

------ For reference only ---------------------------------- -----


To be honest I looked dynamic proxy , do not really understand and spring of What matters contact , it seems I have to practice in practice . . .
------ For reference only -------------------------------------- - after
configuration, seems to be using annotations do everything to the container , and really do not know how to achieve concrete .
------ For reference only -------------------------------------- -
mainly extend existing business through the use of AOP configuration or annotation mode, when captured will be rolled back when the specified exception ;
Keywords : AOP, abnormal
------ For reference only ---------------------------- -----------
recommend a detailed tutorial Spring chant
------ For reference only ----------------- ----------------------
spring of AOP is implemented by IOC carefully taste, very interesting
----- - For reference only ---------------------------------------



Aspect Oriented Programming
(
AOP
is
Aspect Oriented Program
first letter acronym )

, we know that the object-oriented
characterized by inheritance, polymorphism, and encapsulation. The package requires the functions into different objects to this in the software design
often referred to allocate responsibilities. That fact , so different classes with different design approach. Such code is distributed to a
all classes went. The advantage of this is to reduce the complexity of the code, so that the class can be reused.


But people also found in scattered code , but also increases the repeatability of the code . What does that mean ? For example,
we have two classes , you may need to do logging in each method . By object -oriented design methods , we must
two class methods are added to the contents of the log. Maybe they are exactly the same , but that is because the object-oriented design
meter allows unable to contact between classes , and not be able to unify these duplicate code .


Some might say that easy to handle , ah, we can write this code in a separate class of independent methods , and then
then call in these two classes. However , this way , these two classes with separate classes we have mentioned above coupling , and
It changes will affect these two classes . So, is there any way , let us in when needed , free to join
code? This at runtime , dynamically cut to a specified method of the class code , the programming idea is to specify the location of the
aspect-oriented programming .


In general, we managed to cut into the code fragment specifies the class specified method called facets , and cut into what category, which
method is called the entry point. With
AOP
, we can put the total number of class code , drawn into a slice , until
you need to re- cut the object to change its original behavior.

It would appear that
AOP In fact, just

OOP
supplement only.
OOP
distinguish from the horizontal to one class , but
AOP
object from longitudinal to add specific code. With
AOP
,
OOP
becomes a three-dimensional . If you add a time dimension ,
AOP
so
OOP
original two-dimensional into three-dimensional , and the plane turned into a three-dimensional . Technically speaking,
AOP Basically

is achieved through a proxy mechanism .

AOP
on the programming history can be said to be a milestone on the
OOP
programming is a very useful supplement

------ For reference only ------------------------------ ---------
principle
AOP (Aspect Oriented Programming), which is the aspect-oriented programming techniques. AOP -based IoC based OOP is a useful supplement .
AOP application system will be divided into two parts , the core business logic (Core business concerns) and horizontal general logic , which is called the aspect Crosscutting enterprise concerns, for example, all applications must relate to medium-sized the persistence manager (Persistent), transaction management (Transaction Management), security Management (Security), log management (Logging) and debug Manager (Debugging) and so on.
AOP is becoming the next aura of software development. Use AOP, you can handle aspect of code injection main program, the main purpose is not that usually deal with these main aspect. AOP code can prevent confusion .
Spring framework AOP is a promising technology . As a non- invasive , lightweight AOP framework, you need to use a pre- compiler or other meta tags , you can use it in a Java program . This means that the development team where only one person to deal with AOP framework, others as usual programming.
AOP concepts
Let's define some important concepts AOP start .
- aspects (Aspect): modularization of a concern that this might be another crosscutting concern to achieve multiple objects . J2EE application transaction management is a good example of crosscutting concerns . Aspects with Spring's Advisor or interceptor implementation.
- connection points (Joinpoint): clear during program execution points, such as calling a method or a specific exception is thrown.
- notification (Advice): action at a particular connection point , AOP framework for implementation . Various types of notifications include "around", "before" and "throws" notification. Type of notification will be discussed below. Many AOP frameworks , including Spring interceptors are to make the notification model , maintaining an " around" the interceptor chain connection point.
- the entry point (Pointcut): Specifies a collection notice will be triggered by a series of connected points . AOP framework must allow developers to specify a starting point, for example , the use of regular expressions.
- the introduction (Introduction): Adding methods or fields to be notified of the class . Spring allows the introduction of new interfaces to be notified of any object . For example, you could use an introduction to make any object that implements IsModified interface to simplify cache.
- target (Target Object): Object contains the connection point , also called by notice or proxy object.
- AOP proxy (AOP Proxy): AOP framework creates an object , including notification. In Spring , AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
- weaving (Weaving): Assembly aspects to create an advised object. This can be done at compile time ( for example, using AspectJ compiler ) , can also be done at runtime. Spring and other pure Java AOP frameworks, performs weaving at runtime.
various notification types include:
- Around notice : that surrounds a connection point , such as a method call . This is the most powerful notification. Aroud notify perform custom behavior before and after the method call , which is responsible for the implementation of the connection points, or choose to continue to execute short-circuited by returning their own return value or throw an exception.
- Before notice : Notice executed before a connection point, but could not prevent the implementation of this notification before the connection point ( unless it throws an exception ) .
- Throws Notification: Notify the method is executed when an exception is thrown . Spring provides the mandatory notification of Throws , so you can write code to capture interest exception ( and its subclasses ) , does not require a cast from Throwable or Exception.
- After returning Notification: Notify the connection point after normal completion of execution, for example , a method returns without throwing an exception .
Around advice is the most common type of notification . Most interception-based AOP frameworks ( such as Nanning and Jboss 4) only provide Around notice.
as AspectJ, Spring provides all types of notifications , we recommend that you use the most appropriate type of notification to achieve the desired behavior . For example , if you just need to use the return value of a method to update the cache , you'd realize an after returning notification , rather than around notice , although around advice can accomplish the same thing. Use the most appropriate type of notification so easy programming model , and can reduce the potential for errors. For example , you do not need to call in using the required notification MethodInvocation around the proceed () method , and therefore call failed.
concept is the key entry point for AOP , it makes use of AOP interceptors from other technologies . OO -independent entry point so that the level of notification selected targets . For example , to provide declarative transaction management around notifications can be applied to multiple objects across a set of methods . Therefore, the structural elements constitute the starting point of AOP .
interceptor ( also known as interceptors )
interceptor (Interceptor), is AOP (Aspect-Oriented Programming) is another name . AOP is a language in itself , but we are using a JAVA-based integrated into the Spring of SpringAOP. Similarly, we will come to understand through our example alien concept .

 接口类
Java代码     
1. <SPAN style="FONT-SIZE: medium">package com.test.TestSpring3;   
2.   
3. public interface UserService // 被拦截的接口   
4. ...{   
5.     public void printUser(String user);   
6. }   
7. </SPAN>  
 实现类
Java代码     
1. <SPAN style="FONT-SIZE: medium">package com.test.TestSpring3;   
2.   
3. public class UserServiceImp implements UserService // 实现UserService接口   
4. ...{   
5.     public void printUser(String user) ...{   
6.         System.out.println("printUser user:" + user);// 显示user   
7.     }   
8. }   
9.   
10. </SPAN>  
 AOP拦截器
Java代码     
1. <SPAN style="FONT-SIZE: medium">package com.test.TestSpring3;   
2.   
3. import org.aopalliance.intercept.MethodInterceptor;   
4. import org.aopalliance.intercept.MethodInvocation;   
5.   
6. public class UserInterceptor implements MethodInterceptor   
7. // AOP方法拦截器   
8. ...{   
9.   
10.     public Object invoke(MethodInvocation arg0) throws Throwable ...{   
11.   
12.         try ...{   
13.   
14.             if (arg0.getMethod().getName().equals("printUser"))   
15.             // 拦截方法是否是UserService接口的printUser方法   
16.             ...{   
17.                 Object[] args = arg0.getArguments();// 被拦截的参数   
18.                 System.out.println("user:" + args[0]);   
19.                 arg0.getArguments()[0] = "hello!";// 修改被拦截的参数   
20.   
21.             }   
22.   
23.             System.out.println(arg0.getMethod().getName() + "---!");   
24.             return arg0.proceed();// 运行UserService接口的printUser方法   
25.   
26.         } catch (Exception e) ...{   
27.             throw e;   
28.         }   
29.     }   
30. }   
31. </SPAN><SPAN style="FONT-SIZE: medium">   
32. </SPAN>  
 测试类
Java代码     
1. <SPAN style="FONT-SIZE: medium">package com.test.TestSpring3;   
2.   
3. import org.springframework.beans.factory.BeanFactory;   
4.   
5. import org.springframework.beans.factory.xml.XmlBeanFactory;   
6. import org.springframework.context.ApplicationContext;   
7. import org.springframework.context.support.ClassPathXmlApplicationContext;   
8. import org.springframework.context.support.FileSystemXmlApplicationContext;   
9. import org.springframework.core.io.ClassPathResource;   
10. import org.springframework.core.io.Resource;   
11. import org.springframework.web.context.support.WebApplicationContextUtils;   
12.   
13. public class TestInterceptor ...{   
14.   
15.     public static void main(String[] args) ...{   
16.         ApplicationContext ctx = new FileSystemXmlApplicationContext(   
17.                 "classpath:applicationContext.xml");   
18. //        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");       
19.            
20.         UserService us = (UserService) ctx.getBean("userService");   
21.         us.printUser("shawn");   
22.   
23.     }   
24. }</SPAN><SPAN style="FONT-SIZE: medium">   
25. </SPAN>  
 配置文件
 
   
Xml代码     
1. <SPAN style="FONT-SIZE: medium"><?xml version="1.0" encoding="UTF-8"?>  
2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
3. <beans>  
4.     <bean id="userServiceImp"  
5.         class="com.test.TestSpring3.UserServiceImp" />  
6.   
7.     <bean id="userInterceptor" class="com.test.TestSpring3.UserInterceptor" />  
8.   
9.     <bean id="userService"  
10.         class="org.springframework.aop.framework.ProxyFactoryBean">  
11.       <!-- 代理接口 -->  
12.         <property name="proxyInterfaces">  
13.             <value>com.test.TestSpring3.UserService</value>  
14.         </property>  
15.        <!-- 目标实现类 -->  
16.         <property name="target">  
17.             <ref local="userServiceImp" />    
18.       </property>  
19.         <!-- 拦截器 -->  
20.         <property name="interceptorNames">  
21.             <list>  
22.                 <value>userInterceptor</value>  
23.             </list>  
24.         </property>  
25.     </bean>  
26.   
27. </beans>  
28. </SPAN>  
 
 输出:
  user:shawn
   printUser---!
  printUser user:hello!


------ For reference only ----------------------------------- ----
Conclusion: the method is called when the value passed was intercepted modified.
interceptor in the transaction management (transaction interceptor )
If you do not use the mechanism to intercept machine when using JDBC for database access , there are two cases :
• This is the JDBC driver is automatically submitted to the default mode , each database operations (CRUD) Upon successful completion , both as a separate transaction auto-commit If not successfully completed, that throws SQLException words , only the most recent one operation will be rolled back. procedures needed to control the way the non- automatic submission
• This is to better control the transaction :
o Before any operation setAutoCommit the transaction unit (false)
o Upon successful completion of the transaction unit commit ()
o exception occurs after the rollback ()
autocommit mode is not recommended , because each operation will generate a transaction point , which for large applications, performance will be affected ; Again, the common business logic , this model seems powerless . For example:
transfer, the account is removed from A $ 100 deposit will be its B account ; between these two operations if an error occurs , the user A will lose $ 100 , but should have to account B , but because failure to the bank .
Therefore , it is recommended that all applications, if you use JDBC will have to submit a non- automatic mode ( you should be able to find that in our JDBC example we used is the automatic submit model, we are in order to focus on JDBC, rather than on transaction processing ) , that we have in each method :
Java code
1. try {
2. / / After obtaining connections for non- auto-commit mode immediately by calling setAutoCommit (false) the transaction set / / Prepare Query to fetch ; the user Information
3 pst = conn.prepareStatement (findByName).;
4. / / ... ; conn.commit ();
5.} catch (Exception ex) {
6 conn.rollback ().;
7 throw ex.;
8.} finally {
9. try {
10. / / Close Result Set and Statement
11 if (rset = null!) rset.close ().; ;
12 if (pst = null!) pst.close ().; ;
13.} catch (Exception ex) { ;
14 ex.printStackTrace ().;
15. throw new Exception ("SQL Error while closing objects =" + ex. toString ());
16.}
17.}
18.

this code appears to be advocates in AOP "dirty " code . They believe that all matters relating to methods and should be centralized configuration ( see declarative transaction control ) , and automatically intercept procedures should be concerned about their main task , namely, business logic , rather than transaction processing code and mix together .

I look at is how do intercept Spring :
Spring built-in support for transaction processing interceptor
here because JpetStore project to use the code , we will list the entire contents applicationContext.xml :


- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml 's "contextConfigLocation").

application context definition Jpetstore , including transaction management and cited in dataAccessContext-local/jta.xml ( which depends on the specific use of web.xml 'contextConfigLocation' configuration ) registered DAO
->
xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns: aop = "http://www.springframework.org/schema/aop"
xmlns: tx = "http://www.springframework.org/schema/tx"
xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/ beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop- 2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd ">


<-! ========================= GENERAL DEFINITIONS ========================= - >

<-! Configurer that replaces $ {...} placeholders with values ​​from properties files property file values ​​
placeholder extracted from listed
->
<-! (in this case, mail and JDBC related properties) ->



WEB-INF/mail.properties ;
WEB-INF/jdbc.properties ;




<-! MailSender used by EmailAdvice
designated javamail implementers to send mail , here comes the realization of the use of the spring . Use this bean will be emailAdvice
->






<-! ========================= BUSINESS OBJECT DEFINITIONS ======================== ->

<-! do not need to , because they were using SpringMVC realization Generic validator for Account objects, to be used ; for example by the Spring web tier ->


<-! do not need to , because they were using SpringMVC realization Generic validator for Order objects, to be used ; for example by the Spring web tier ->


major business logic objects , objects that we call the facade
inject all the DAO, which is a reference to the DAO DAO dataAccessContext-xxx.xml defined
facade object transaction control all methods through the following aop: config be controlled

- JPetStore primary business object (default implementation).
- Transaction advice gets applied through the AOP configuration below.
->









<-! ========================= ASPECT CONFIGURATION ======================== - >
<-! AOP configuration to control which methods will need to be a transaction , using AspectJ syntax - >

This definition creates auto-proxy infrastructure based on the given pointcut,
expressed in AspectJ pointcut language Here:. applying the advice named
"txAdvice" to all methods on classes named PetStoreImpl.
->
<-! pointed out that all methods will be used in PetStoreFacade are txAdvice ( defined in the immediately following elements









.

2 条评论:

  1. Rs2hot has a large stock of Runescape Gold with cheap prices, fast delivery and professional services, is a trustworthy RS Gold store with a great reputation in the market.Buy OSRS Gold , RS 07 Stuff & Items , RS 3 Equipment & Weapons, Runescape Gold, RS Gold, RSGP, Buy Runescape Gold from rs2hot, choosing rs2hot to Buy Runescape Gold will never let you down.
    [url=https://www.rs4uk.com/runescape-2007-gold/]osrs cheap gold[/url]
    [url=https://www.rs4uk.com/runescape-2007-gold/]buy rsgp[/url]
    [url=https://www.rs4uk.com/runescape-2007-gold/]buying old school runescape gold[/url]
    [url=https://www.rs4uk.com/runescape-gold/]runescape gold swap[/url]
    [url=https://www.rs4uk.com/runescape-gold/]buying gold runescape[/url]

    回复删除
  2. [url=https://www.rs2hot.com/]osrs to rs3 gp[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]osrsgp[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]osrunescape[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]play runescape classic[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]play runescape old school[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]real cheap gold[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]rold school runescape[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]rs 07[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]rs 07 gold[/url]
    [url=https://www.rs2hot.com/rs2007-gold/]rs 2007[/url]

    回复删除