Spring| | Interview

Source: Internet
Author: User
Tags throwable

1. Dependency Injection (DI) (IOC)

  

The object itself is not responsible for object creation and maintenance, transferring control to external container implementations, reducing program coupling, providing only Java methods for the container to determine dependencies, and dependent objects passing through the JavaBean attribute or constructor to the desired object, using <bean> element to construct the component, a unique name is defined for the ID, which is implemented by invoking the property's setter method.

In a variety of ways to achieve dependency injection, divided into construction injection, p-named injection;

Construction injection

Use <constructor-arg> to define DAO implementations in Applicationcontext.xml, using the Index property to specify the indexes for that location, and to provide the type attribute to differentiate between strings and basic data types, in a sequential way.

P Named injection

P:propertyname= "Variable"

Inject data type <value/> inject empty string, <null/>=>null

2. Enhanced Type

Exception throw Enhancement

 Public Static  Implements throwsadvice{         void  affterthrowing (Method method,object[]args,object Target, SQLException ex);      void afterthrowing (SQLException ex);           void afterthrowing (Runntimeexception ex);}    

Surround enhancement

Before and after the target method can be woven into the enhancement, it is simply to strengthen the transfer of control rights.

 Public class Implements methodinterceptor{@Override    Object Invoke (methodinvocation arg0) {    ... Try {      arg0.proceed ();   } Catch (Throwable e) {      ...} }}

Annotation definition Enhancements

Spring implements annotation enhancements through @acpectj, with new features in AspectJ5,

@Aspect  Public class bizlogger{     @Before ("Execution (* biz). biz.* (..)) " )   void  before () {   } @AfterReturning("Execution (* biz. biz.* (..)) "  void  afterruterning () {    ...}       }

@Before define before as a predecessor enhancement, @AfterReturning define afterreturning () as a post-enhancement

Also need to define the configuration file in Applicationcontext.xml

Class= "Class"/>

Surround enhancement can also be defined by annotations

@Aspect class aroundlogger{@Around ("Execution (..)"  Try{    Object result= jp.procees ();} Catch (Throwable ex) {} }}

3.SessionFactory

You need to provide a relational mapping file for an object after you specify the file location for Org.springframework.orm.hibernate3.LocalSessionFactoryBean by defining class

  

<property name= "Mappingdirectorylocations" >  <list>   <value>classpath:path</values ></list></property>

Development of a hibernatetemplate interface for DAO business development

 Public class extends Implements dao{      void  Update (object entity);   void Delete (Object entity);  Object  getclass (Class entityclass,serializable ID);   void saveorupdate (Object entity);}

4. Transaction processing

Easily complex in hard-coded, spring provides transactional processing for code-to-business separation, reducing development and maintenance difficulties by configuring TX and AOP for transactional operations

By defining the <tx:advice id= "" transaction-manager= "> Define transaction labels in the Bean label, you can customize the transaction properties by <tx:attributes>, with the following label

Propagation: Transaction Propagation

    • REQUIRED: Default value, if there is a transaction, the current transaction is supported, if no one is created
    • Support: If there is a supported current transaction, if it is not performed on a non-transactional basis
    • MANDATORY: Support exists, no exception thrown
    • Requires_new always open a transaction, there is a hang, no new transaction is executed
    • not_supported non-transactional execution, presence pending
    • Never: Non-transactional execution
    • NESTED: Create nested transaction no longer in current active transaction

Isolation: Transaction ISOLATION level defaults to default

Read-only: Whether the transaction is read-only

Rollback-for: Set rollback exception

No-rollback-for: Set no rollback exception type

5.web.xml

Contextloaderlistener

Spring needs to provide a listening service to control container creation in Web. xml

<context-param>    <param-name>contextConfigLocation</param-name>   <param-value> classpath:applicationcontext.xml</param-value></context-param><!--Add listener service-->< Listener>  <listener-class>org.springframework.web.context.contextloaderlistener</ listener-class>  </listener-class> </listener>

Opensessioninviewfilter

The function binds the hibernate session and a complete request process to ensure that a session is always open during a single request, solving problems such as delayed loading.

<fillter>  <filter-name>OpenSessionInViewFilter</filter-name>   <filter-class >     org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class ></filter><filter-mapping>    <filter-name>opensessioninviewfilter</filter-name >     <url-pattern>/*</url-pattern></filter-mapping><!--need to be in struts Strutsprepareandexecutefilter front, otherwise it won't work--

6.Bean Scope

In addition to the bean can be injected, you can also specify the scope, determine the spring's build strategy, affecting the program's operational efficiency and data security are divided into 5 kinds

Snigleton: Default value, create instance in Singleton, ensure only one instance, reduce burden for GC

Prototype: Creates an instance each time a bean is fetched from the container

Request:for Web, creating an instance for HTTP requests

Session:web sharing an instance of the same session, using different instances for different sessions

Global Session: Share an instance with the same global only on the Portlet's web.

7.JNDI

Spring provides a jndiobject ' Factorybean class for drinking Jndi resources

<Context>  <resource name= "Jdbc/jboa" auth= "Container"         type= "Javax.sql.DataSource"          driverclassname= "..."         user-"password=" "</Context><!--DataSource -- Class= "Org.springframework.jndi.JndiObjectFactoryBean" >

8. Annotations Sessionfactory

By defining Annotationsessionfactorybean configuration annotations, which are localsessionfactorybean subclasses, you need to configure

<bean id= "Sessionfactory"   class to Scan--><property name= "Packagestoscan" Value= "Entity"/>

9. Automatic assembly

When too much configuration is required, automated assembly enables Autowire to be automatically assembled, and the following properties can be configured

No automatic configuration is not used

Bytype is automatically assembled according to attributes, if there is a dependency property type is automatically assembled, if there is more than one throw a field, if there is no matching bean, the property will not be set

ByName is configured based on the property name to find the bean that matches the setter method of the attribute and finds the auto-injection

Constructor: Applies to construct parameters, and throws an exception if no consistent bean is found.

Reduced maintenance injection by using Default-autowire

10. Dependency Checking

You can use dependency checking to ensure that the bean properties are set correctly, and the global dependency check is set by <dependeny-check> or Default-dependency-check. has a correlation property

None: no dependency checking

Obejcts: Checking the dependencies of other beans in the beanfactory

Sunple checking the original

All: Simultaneous check

11. Annotation Definition Bean

Mapping configuration with @component

@Repository for labeling DAO classes

@Serive for labeling Business classes

@Controller for labeling Controllers

@Qualifier used to label by name matching method

@AutoWired for automatic Assembly

@Scope to match with the action

When you need to work with annotations, you need to configure the following in XML

1. Add a context namespace

2. Label the class in the scan package

<context-component-scaan base-package = "*" >

You can also configure transactions with annotations

<tx:annotation-driven transaction-manager= "Txmanager" >

Add the @transactional implementation to the business method with the following characteristics

1. Propagation Settings propeagation_required

2. Isolation level is Isolation_default

3. Transaction is R/W

4. Time-out defaults since transaction processing

Spring| | Interview

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.