Spring Face questions

Source: Internet
Author: User
Tags to domain

First, spring working principle:

1.spring MVC requests that all requests be submitted to Dispatcherservlet, which will delegate the other modules of the application system responsible for the actual processing of the request.
2.DispatcherServlet queries one or more handlermapping to find the controller that handles the request.
3.DispatcherServlet request Submit to target Controller
4.Controller after the business logic is processed, it returns a Modelandview
5.Dispathcher querying one or more viewresolver view resolvers, locating the View object specified by the Modelandview object
6. The View object is responsible for rendering back to the client.

Second, why use spring:

AOP allows developers to create non-behavioral concerns, called crosscutting concerns, and insert them into application code. With AOP, public services (such as logs, persistence, transactions, and so on) can be decomposed into facets and applied to domain objects without increasing the complexity of the object model of the domain object.

IOC allows you to create an application environment where objects can be constructed, and then pass their collaboration objects to those objects. As the word inversion shows, the IOC is like the reverse JNDI. Not using a bunch of abstract factories, service locators, single elements (singleton), and direct constructs (straight construction), each object is constructed with its collaboration objects. Therefore, the collaboration object (collaborator) is managed by the container.

Spring even an AOP framework, is also an IOC container. The best part of Spring is that it helps you replace objects. With Spring, you simply add dependencies (collaboration objects) with the JavaBean property and configuration file. You can then easily replace collaboration objects with similar interfaces when you need them.

Three, please talk about SSH integration:

Ssh:
Struts (presentation layer) +spring (business layer) +hibernate (persistence layer)
Struts:
Struts is a presentation-layer framework that mainly functions as interface display, receiving requests, and distributing requests.
In the MVC framework, struts belongs to the VC level, responsible for the interface performance, responsible for the distribution of MVC relationship. (View: Jsp,http,form,tag,resourse;controller:actionservlet,struts-config.xml,action)
Hibernate:
Hibernate is a persistent layer framework that is only responsible for operations with relational databases.
Spring:
Spring is a business-layer framework that is an integrated framework that is well-bonded to the presentation and persistence layers.

Iv. Introduction to Spring's transaction management:

A transaction is a uniform commit or rollback operation for a series of database operations (such as inserting multiple data), and if the insert succeeds, it succeeds, and if there is an exception in the middle, all actions before the rollback.
This prevents dirty data from occurring and prevents problems with database data.
In development, transaction management is generally done to avoid this situation. Spring also has its own transaction management mechanism, typically managed using Transactionmananger, which can be done through spring injection.

Spring provides several classes for transaction processing:
Transactiondefinition//Transaction Property Definition
Transcationstatus//Represents the current transaction, which can be committed and rolled back.
Platformtransactionmanager This is the underlying interface that spring provides for managing transactions, with an implementation of an abstract class Abstractplatformtransactionmanager, The transaction management classes we use, such as Datasourcetransactionmanager, are 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 that spring provides can be divided into two categories: programmatic and declarative. Programmatic, more flexible, but the code is large, there are more duplicate code, declarative more flexible than the programming type.

Programming mainly uses Transactiontemplate. Omit a partial commit, rollback, a series of transaction object definitions, to be injected into the transaction management object.
void Add () {
Transactiontemplate.execute (New Transactioncallback () {
Pulic Object dointransaction (transactionstatus ts)
{//do STH}
}
}

Declarative:

Using Transactionproxyfactorybean:

propagation_required propagation_required propagation_required,readonly

Dynamic agents around POxy are able to automatically commit and rollback transactions
Org.springframework.transaction.interceptor.TransactionProxyFactoryBean

propagation_required– supports the current transaction and creates a new transaction if there is no current transaction. This is the most common choice.

propagation_supports– supports the current transaction and is executed in a non-transactional manner if no transaction is currently in use.

The propagation_mandatory– supports the current transaction and throws an exception if there is no current transaction.

propagation_requires_new– a new transaction, suspending the current transaction if a transaction is currently present.

The propagation_not_supported– executes the operation in a non-transactional manner, suspending the current transaction if a transaction is currently present.

The propagation_never– is executed in a non-transactional manner and throws an exception if a transaction is currently present.

propagation_nested– executes within a nested transaction if a transaction is currently present. If there is currently no transaction, do something similar to propagation_required.

V. How to configure database driver in spring?

Use the "Org.springframework.jdbc.datasource.DriverManagerDataSource" data source to configure the database driver. Examples are as follows:
<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>sa</value></property>
<property name= "Password" ><value></value></property>
</bean>

VI, spring inside the Applicationcontext.xml file can be changed to another file name?

Contextloaderlistener is a servletcontextlistener that is initialized when your web app starts. By default, it will find 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". Examples are as follows:

<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>

How do I configure spring in a Web application?

Add the following in the Web. XML to load the contents of the/web-inf/applicationcontext.xml when you start the server.
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
Org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Get ApplicationContext instances with the following classes
Webapplicationcontextutils.getwebapplicationcontext

How do I define hibernate mapping in spring?

Add Hibernate mapping files to the Applicationcontext.xml file in the Web/web-inf directory. Examples are as follows:
<property name= "Mappingresources" >
<list>
<value>org/appfuse/model/User.hbm.xml</value>
</list>
</property>

Nine, explain dependency injection (DI, Dependency injection) and IOC (inversion of control, inversion of controls)?

Dependency Injection di is a programming pattern and architecture model, sometimes referred to as inversion of control, although, technically, dependency injection is a special implementation of IOC, dependency injection refers to an object applying another object to provide a special ability, For example, a database connection is passed to an object's structure method instead of creating a connection within that object itself. The basic idea of control inversion and dependency injection is to convert class dependencies from inside the class to the outside to reduce dependency
Applying control inversion, when an object is created, it is passed to it by an external entity that regulates all objects within the system, and references the object to which it depends. It can also be said that the dependency is injected into the object. So, control reversal is a reversal of this responsibility about how an object obtains a reference to the object he relies on.

What are the roles of Beanfactory and ApplicationContext in spring?

1. The beanfactory is responsible for reading the bean configuration document, managing the bean's loading, instantiating, maintaining the dependency between the beans, and responsible for the bean's declaration cycle.
2. ApplicationContext provides more complete framework functionality in addition to the functionality provided by the beanfactory above:

A. Internationalization support
B. Resource access: Resource rs = ctx. GetResource ("Classpath:config.properties"), "File:c:/config.properties"
C. Event delivery: By implementing the Applicationcontextaware interface
3. Common ways to get ApplicationContext:
Filesystemxmlapplicationcontext: Created from a file system or URL-specified XML configuration file with an array of configuration file names or file names
Classpathxmlapplicationcontext: Created from the classpath XML configuration file, you can read the configuration file from the jar package
Webapplicationcontextutils: Reading a configuration file from the Web application's root directory requires a configuration in XML. config, which can be configured with a listener or servlet to implement
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Either way, the default profile is Web-inf/applicationcontext.xml, or you can use Context-param to specify the configuration file
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>

Xi. How do I configure a applicationcontext.xml file in a Web environment?

<listener>
<listener-class>
Org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Or:
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
Org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Use the following method to remove the ApplicationContext instance:
ApplicationContext Ac=webapplicationcontextutils.getwebapplicationcontext (This.getservletcontext);

12, how to configure Spring+struts?

Add a plugin to the struts-config.xml and load it through it applicationcontext.xml
? Modify the action-mapping tag in Struts-config.xml, and the specific action is given to Delegateactionproxy
? Enter a spring environment through the delegateactionproxy.
? In spring applicationcontext.xml join <bean name= "/login" class= "" singleton= "false"/>

13. What are the main classes in the Spring+hibernate configuration file?

DataSource
SessionFactory:hibernate.cfg.xml
TransactionManager
Userdao (extends Hibernatedaosupport)
Sessionfactory
Façade
Proxy
Sessionfactory
TransactionManager
Façade

Add the spring environment to the hibernate environment first in MyEclipse.
If spring is combined with hibernate, the Hibernate.cfg.xml file is not required to be correct

14, how to achieve internationalization in spring?

Load a bean in Applicationcontext.xml
<bean id= "Messagesource" class= "Org.springframework.context.support.ResourceBundleMessageSource" >
<property name= "basename" >
<value>message</value>
</property>
</bean>
? Build multiple properties files in src directory
? For non-English to use native2ascii-encoding gb2312 source conversion file related content
? Its naming format is Message_ language _ country.
? The page displays the prompt message, and the key name takes the key value.
? When a given country, the system automatically loads the properties information for the corresponding country.
? The relevant information is removed by Applictioncontext.getmessage ("Key Name", "parameter", "region").

What are the core classes in spring, and what are the roles?

Beanfactory: Create a new instance that can implement a singleton pattern
Beanwrapper: Provides a unified get and set method
ApplicationContext: Provides framework implementations, including all features of the beanfactory

16. What is the role of AOP,AOP?

Aspect-oriented programming (AOP) provides an alternative perspective to think about program structure, which compensates for the lack of object-oriented programming (OOP).
In addition to classes (classes), AOP provides facets. Modular, such as cross-cutting of multiple types and objects, to focus on the transaction management
One of the key components of spring is the AOP framework, which gives you the freedom to choose whether to use AOP
Provides declarative enterprise services, especially in lieu of EJB declarative services. The most important service is declarative transaction management, which is based on spring's abstract management of Things
Allows users to implement custom facets, using AOP to refine the use of OOP
Spring AOP can be seen as an enhancement to spring

17. What are the benefits of using spring?

Spring effectively organizes your middle-tier objects, whether or not you choose to use EJBS. If you just use struts or other frameworks that contain the Java EE-specific APIs, you'll notice that spring is focused on the legacy.

Spring can eliminate the excessive use of singleton in many projects. Based on my experience, this is a major problem, which reduces the testability and object-oriented nature of the system.
Spring eliminates the need to customize files with attributes in a variety of formats, and is configured in a consistent way throughout the application and engineering. Ever confused, a particular class looking for a psychedelic attribute keyword or system attribute, do you have to read Javadoc or even source code? With spring, you can easily see the JavaBean property of the class. The use of inverted controls (discussed below) helps to accomplish this simplification.
Spring can promote good programming habits through interfaces rather than classes, reducing programming costs to almost zero.
Spring is designed so that applications created with it depend as little as possible on his APIs. Most business objects in a spring application are not dependent on spring.
Applications built using spring are easy to unit test.
Spring enables the use of EJBS to be an implementation choice, not an inevitable choice for application architectures. You can choose to use POJOs or local EJBS to implement the business interface without affecting the calling code.
Spring helps you solve many problems without using EJBS. Spring provides an alternative to EJBS that are suitable for many Web applications. For example, spring can use AOP to provide declarative transactions without using an EJB container, if you only need to deal with a single database, and you don't even need a JTA implementation.
Spring provides a consistent framework for data access, whether using JDBC or O/R mapping products such as hibernate.
Spring does enable you to solve your problem with the simplest possible solution. These features are of great value.
To sum up, spring has the following advantages:
Low-intrusive design with very low code contamination
True commitment to write Once,run anywhere, independent of various application servers
Spring's di mechanism reduces the complexity of business object substitution
Spring is not entirely dependent on spring, and developers are free to select part or all of the spring framework

18. What is spring and what are the characteristics of it?

Spring is a lightweight control inversion (IoC) and facet-oriented (AOP) container framework.

Lightweight-Spring is lightweight, both in terms of size and overhead. The full spring framework can be published in a jar file with a size of more than 1MB. and the processing overhead required by spring is negligible. In addition, spring is non-intrusive: Typically, objects in spring applications do not depend on a particular class of spring.

Control reversal--spring facilitates loose coupling through a technique called inversion of Control (IoC). When an IOC is applied, other objects that an object relies on are passed in passively, rather than the object itself creating or locating dependent objects. You can think of the IOC as opposed to Jndi--not the object looking for dependencies from the container, but the container actively passing the dependency to it when the object is initialized without waiting for the object to be requested.
Faceted--spring provides rich support for aspect-oriented programming, allowing for the development of cohesion through the separation of application business logic with system-level services such as auditing (auditing) and transaction () management. The Application object only implements what they should do-complete the business logic-that's all. They are not responsible (or even conscious) for other system-level concerns, such as log or transaction support.
The container--spring contains and manages the configuration and lifecycle of the Application object, in this sense it is a container in which you can configure how each of your beans is created-based on a configurable prototype (prototype), your bean can create a separate instance or each time it needs to be born into a new instance-and how they relate to each other. However, spring should not be confused with traditional heavyweight ejb containers, which are often bulky and cumbersome and difficult to use.
Framework--spring can be used to configure and assemble simple components into complex applications. In spring, application objects are combined declaratively, typically in an XML file. Spring also provides a number of basic functions (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.

19. Please describe the Bean's life cycle in the spring framework

First, the bean definition
Spring typically defines a bean through a configuration file. Such as:

<?xml version= "1.0″encoding=" utf-8″?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd ">
<bean id= "HelloWorld" class= "Com.pqf.beans.HelloWorld" >
<property name= "MSG" >
<value>HelloWorld</value>
</property>
</bean>
</beans>

This configuration file defines a bean that is identified as HelloWorld. Multiple beans can be defined in a configuration document.

Second, the initialization of the bean
There are two ways of initializing a bean.
1, in the configuration document by specifying the Init-method property to complete
Implement a method in the Bean's class that initializes the bean properties, such as Init (), such as:
public class helloworld{
Public String Msg=null;
Public Date Date=null;

public void init () {
Msg= "HelloWorld";
Date=new Date ();
}
......
}
Then, set the Init-mothod property in the configuration file:
<bean id= "HelloWorld" class= "Com.pqf.beans.HelloWorld" init-mothod= "init" >
</bean>

2. Implement Org.springframwork.beans.factory.InitializingBean interface
The bean implements the Initializingbean interface and adds the Afterpropertiesset () method:

public class HelloWorld implement Initializingbean {
Public String Msg=null;
Public Date Date=null;

public void Afterpropertiesset () {
msg= "Say hello to the world! ”;
Date=new Date ();
}
......
}

Then, when all the properties of this bean are set by spring's beanfactory, the Afterpropertiesset () method is automatically called to initialize the bean, so the configuration file does not have to specify the Init-method attribute.

Third, the Bean call
There are three ways to get a bean and make a call:
1. Using Beanwrapper
HelloWorld hw=new HelloWorld ();
Beanwrapper bw=new Beanwrapperimpl (HW);
Bw.setpropertyvalue ("msg", "HelloWorld");
System.out.println (Bw.getpropertycalue ("MSG"));

2. Using Beanfactory
InputStream is=new fileinputstream ("config");
Xmlbeanfactory factory=new xmlbeanfactory (IS);
HelloWorld hw= (HelloWorld) Factory.getbean ("HelloWorld");
System.out.println (Hw.getmsg ());

3. Using Applicationconttext
ApplicationContext actx=new flesystemxmlapplicationcontext ("config");
HelloWorld hw= (HelloWorld) Actx.getbean ("HelloWorld");
System.out.println (Hw.getmsg ());

Iv. The destruction of beans
1. Using the Destory-method attribute in the configuration file
Similar to the initialization property Init-methods, implements a method of undoing the bean in the bean's class, and then specifies it through Destory-method in the configuration file, and spring automatically invokes the specified destroy method when the bean is destroyed.

2. Implement Org.springframwork.bean.factory.DisposebleBean interface
If the Disposeblebean interface is implemented, spring will automatically invoke the Destory method in the bean to destroy it, so the Destory method must be provided in the bean.

20. Some important concepts in AOP are explained in terms of:

  • Facets (Aspect): A focus of modularity, which may be crosscutting across multiple objects. Transaction management is a good example of a crosscutting concern in the Java EE application. In spring AOP, facets can be implemented using generic classes (pattern-based styles) or @Aspect annotations (@AspectJ styles) in ordinary classes.

  • Connection point (Joinpoint): a particular point in the execution of a program, such as when a method is called or when an exception is handled. In spring AOP, a connection point always represents the execution of a method. By declaring a parameter of type org.aspectj.lang.JoinPoint , you get the connection point information for the body part of the notification (Advice).

  • Notification (Advice): An action performed on a particular connection point (joinpoint) of a slice. Notifications are available in various types, including notifications such as "Around", "before", and "after". The type of notification is discussed later in this section. Many AOP frameworks, including spring, are notification models with interceptors, and maintain a chain of interceptors centered on the connection point.

  • Pointcut (Pointcut): an assertion that matches a connection point (Joinpoint). The notification is associated with a pointcut expression and runs on the connection point that satisfies the pointcut (for example, when a method for a particular name is executed). How Pointcut expressions match connection points is the core of AOP: Spring defaults to using the ASPECTJ pointcut syntax.

  • Introduced (Introduction): (also known as an internal type declaration (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 introduction to make the bean implement the ismodified interface to simplify the caching mechanism.

  • Target object: An object that is notified (advise) by one or more facets (aspect). It is also called the notified (advised) object. Since spring AOP is implemented by the runtime proxy, this object is always a proxy (proxied) object.

  • AOP Proxy: An object created by the AOP framework to implement a facet contract (aspect contract), including functions such as notification method execution. In spring, an AOP proxy can be either a JDK dynamic agent or a cglib proxy. Note: The latest introduction to Spring 2.0 is the pattern-based (schema-based) style and @aspectj annotation style facet declarations, which are transparent to the users who use these styles.

  • Weaving (Weaving): Connects a facet (aspect) to another application type or object and creates an object that is notified (advised). These can be done at compile time (for example, with the AspectJ compiler), at class load time, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.

Type of notification:

    • Pre-notification (before advice): A notification that is executed before a connection point, but this notification does not prevent execution before the connection point (unless it throws an exception).

    • Notification after return (after returning advice): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally.

    • Notification after an exception is thrown (after throwing advice): the notification that is executed when the method throws an exception exits.

    • Post notification (after (finally) advice): A notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit).

    • Surround notification (Around Advice): A notification that encloses a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom behavior before and after a method call. It also chooses whether to continue executing the connection point or to return directly to their own return value or throw an exception to end the execution.

Surround notification is one of the most common types of notifications. Most interception-based AOP frameworks, such as Nanning and JBOSS4, provide only surround notifications.

The concept of pointcut (pointcut) and connection point matching is the key to AOP, which makes AOP different from other old technologies that simply provide interception functionality. The pointcut enables the location notification (advice) to be independent of the OO hierarchy. For example, a around notification that provides declarative transaction management can be applied to a set of methods that span multiple objects, such as all business operations at the service layer.

Spring Face questions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.