[Spring] Spring Study Notes 1-Basic Knowledge

Source: Internet
Author: User
Use eclipse to build a Maven springmvc Project

Http://blog.csdn.net/chjttony/article/details/6026079

 

1. in the Java development field, spring is a lightweight and non-invasive Java Development Framework compared with EJB, there were two best-selling books, "expert one-on-one J2EE design and development" and "expert one-on-one j2eedevelopment without EJB", which are a must-have guide for advanced Java experts., spring is developed from the theory of these two books.

The main core of spring is:

(1 ). control inversion (IOC): In the traditional Java development mode, when an object is required, we use new or getinstance to directly or indirectly call the constructor to create an object, in spring development mode, the spring container uses the factory mode to create the required objects for us. We do not need to create the required objects for use, directly call the objects provided by spring for us. This is the idea of controlling reversal. There are three ways to instantiate a Java object: Class constructor, static factory method, and instance factory method. When spring is used, we do not need to worry about how to instantiate an object, spring automatically instantiates an object for us through the control inversion mechanism.

(2 ). dependency injection (DI ): spring uses the Set Method of the Java Bean object or the constructor with parameters to set the required values for its attributes when creating the required object. This is the basic idea of dependency injection.

(3) Aspect-oriented programming (AOP): In the idea of Object-Oriented Programming (OOP), we abstract things vertically into objects one by one. In Aspect-Oriented Programming, We horizontally abstract some similar aspects of an object into one aspect, and perform some permission verification and transaction management on this aspect, the process of logging and other public operations is the idea of Aspect-Oriented Programming.

2. in spring, all managed objects are JavaBean objects, while beanfactory and applicationcontext are two IOC containers of the Spring framework. Currently, applicationncontext is generally used, which not only includes the role of beanfactory, at the same time, more extensions are also carried out.

Simple Method to instantiate Spring IoC container:

(1). Method 1:

// If there is only one spring configuration file, you can directly pass a string parameter without using the array applicationcontext context = new classpathxmlapplicationcontext (New String [] {"Spring configuration file path "});

(2). Method 2:

Resource res = new filesystemresource ("Spring configuration file"); beanfactory factory = new xmlbeanfactory (RES );

2. Spring configuration file combination method:

Most of the time, because spring requires a lot of management and configuration items, if they are all put in a configuration file, the configuration file will become relatively large and inconvenient to maintain, the general good practice is to separate the spring configuration file according to the functional module, for example: Dao layer configuration to a spring-dao.xml configuration file, service layer configuration to the spring-service.xml file, struts action configuration to the spring-action.xml file, and then combine these scattered configuration files in the following two ways:

(1). Method 1: Before defining the <bean> element in the spring configuration file, use the <import> element to introduce other spring configuration files, for example:

<beans>       <import resource=”spring-dao.xml”/>       <import resource=”spring-service.xml”/>       <import resource=”spring-action.xml”/>       ……       <bean>       </bean>       ……</beans>

(2). Method 2:

A. For javase projects, when you use the following method to obtain the applicationcontext object, all spring configuration files are transmitted through arrays. You can also use wildcards such as spring-*. xml.

Applicationcontext context = new classpathxmlapplicationcontext (New String [] {"Spring configuration file path "});

B. For Java EE projects, multiple spring configuration files can be specified in the web. xml file, separated by commas (,), or wildcards.

3. Spring configuration file bean configuration rules:

(1) A bean can be uniquely specified and referenced by an ID attribute. If there are more than two identical IDs in the spring configuration file, spring will report an error of ID conflict.

(2 ). A bean can also be referenced and specified through a name attribute. If there are more than two beans with the same name in the spring configuration file, during runtime, the bean reference with the same name will be automatically overwritten, and no error will be reported.

4. Spring dependency injection:

When configuring a bean in spring, if you need to provide some initialization parameters for the bean, you need to use the dependency injection method, the so-called dependency injection is the process of passing some bean parameters to bean instance objects through spring. Spring dependency injection can be implemented in three ways:

(1). Use the constructor to inject:

<Bean id = "......" Class = "……"> <Constructor-Arg> parameter 1 required by the constructor-Arg> <constructor-Arg> parameter 2 required by the constructor-Arg> ...... </Bean>

When using the constructor injection method: Spring calls the constructor that matches the configuration parameters when instantiating the bean.

(2). Use setter injection of properties:

<Bean id = "......" Class = "……"> <Property name = "property 1" value = "......" /> <Property name = "Property 2" value = "......" /> ...... </Bean>

When the setter injection method of the attribute is used, the injected attribute must provide the setter and getter methods. Spring will automatically call the construction method without parameters or static factory methods during instantiation, after instantiation, the Set Method of the attribute is automatically called to set the value.

(3 ). field field injection is a Java annotation-based injection method provided after spring2.5, spring dependency injection is performed by using Annotations on fields in Java or the setter method.

For example:

A. Field Injection:

@Resourceprivate  UserDao dao;

B. Property injection:

@Resourcepublic void setUserDao(UserDao dao){       this.dao = dao;}

5. Spring injects bean-dependent methods through injection:

When one bean is injected into another bean on which it depends in spring, another bean is injected using ref. A simple example is as follows:

If bean1 is referenced by the bean1 attribute in bean2, inject the following method:

<Beans> <bean id = "bean1" class = "…"> <Property name = "property 1" value = "......" /> ...... </Bean> <bean id = "bean2" class = "……"> <Property name = "bean1" ref = "bean1"/> ...... </Bean> </beans>

6. Spring Collection injection:

Spring also provides the following methods to inject values into Bean collections:

(1). Set set injection:

<bean id=”……” class=”……”><set>              <value>value1</value>              <value>value2</value>              ……       </set></bean>

(2). List set injection:

<bean id=”……” class=”……”><list>              <value>value1</value>              <value>value2</value>              ……       </list></bean>

(3). Map set injection:

<bean id=”……” class=”……”><map>              <entry key=”key1” value=”value1”>              <entry key=”key2” value=”value2”>              ……       </map></bean>

(4). properties injection:

<bean id=”……” class=”……”><props>              <prop key=”key1”>value1</prop>              <prop key=”key2”>value2</prop>              ……       </props></bean>

Note: spring automatically converts its data type and supports generics.

8. Java annotation (annotation) Brief Introduction:

The Java annotation (annotation) is to add a tag field to the Java source file, and then obtain these tag fields and their tag targets during compilation or running through reflection, then the corresponding processing method is used. The XDoclet that was once popular is the earliest explanation of the working principle of Java annotations. Annotations can be used for some configurations, which greatly reduces the trouble of writing xml configuration files. However, some people think that the annotation method is not easy to understand and maintain. Therefore, the annotations vs. xml configuration files have been constantly debated, I feel that there is no difference between good and bad. The right is the best.

(1) JDK built-in Annotations:

JDK has three built-in Annotations:

A. @ override: declares that a method is overwritten.

B. @ deprectated: it is not recommended to declare that a method is outdated.

C. @ suppresswarning ({"unchecked ",.......}) : Tells the compiler to ignore the warning information.

(2). Custom Java Annotations:

Java annotation is a special interface. It is very convenient to customize Java annotations. A simple example is as follows:

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.CLASS)public @interface TestAnnotation{String value() default “”;}

(3) If you want to inherit a custom annotation, add the "@ inherited" annotation to the custom annotation class.

Note and note:

A. Java annotations automatically inherit the java. Lang. annotation. annotation interface. Therefore, other annotations or interfaces cannot be inherited during custom annotations.

B. Retention: Tell the compiler how to process the annotation, that is, when the annotation runs.

Retentionpolicy is an enumeration type and has the following three status values:

1). Source: The annotation is stored in the source file and is discarded after compilation.

2). Class: This annotation is stored in the class file and is its default value.

3). runtime: The annotation is stored in the class file, and the Java Virtual Machine reads and parses the annotation. This type is very important. You can use the reflection mechanism to obtain annotation-related information and perform program analysis and processing.

C. @ target: Specifies the object to use for the annotation.

Elementtype is also an enumeration type, which has the following status values:

1). Type: This annotation applies to class, interface, Enum and other class-level target objects.

2). Field: This annotation applies to the target object at the field level in the class.

3). Method: This annotation applies to the target object at the method level in the class.

4). Parameter: This annotation applies to the target object at the method parameter level.

5). constructor: This annotation applies to class constructor.

6). local_variable: This annotation applies to local variables.

7). annotation_type: This annotation applies to annotation objects.

8). Package: This annotation applies to package objects.

D. Only attributes can be declared in the annotation, but methods cannot be declared. The methods for declaring attributes are special:

Syntax format: Data Type attribute () default value (default value is optional); for example, stringvalue ();

When used, the "annotation object (attribute = attribute value)" specifies the attribute value for the annotation, and the value of the annotation attribute can be obtained through "annotation object. Attribute.

E. annotation parsing: The annotation object can be obtained by using the Java reflection mechanism to obtain the annotation target object, such:

If the field object field of the annotation target is obtained through reflection, the annotation object can be obtained through "field. getannotation (annotation class. Class.

9. annotation-based Spring configuration preparation conditions:

Since spring2.5, spring has fully supported annotation configuration, so you do not need to write xml configuration files. You can also use spring.

(1). To use the spring annotation method, you must add the jar package that spring annotation method depends on: common-annotation.jar.

(2) When using annotation, you must add the annotation namespace in the schema of the spring configuration file as follows:

xmlns:context=”http://www.springframework.org/schema/context”http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd

(3) register the annotation processor in the spring configuration file:

Add the following before the <. bean> element in the spring configuration file:

<context:annotation-config>

10. annotation-based Spring Configuration:

Spring uses four annotations to configure bean by function: the class marked by the following four annotations is equivalent to the bean configured in the XML document.

(1). @ component: Refers to a component. It is used for Java Beans that are generally not categorized.

(2). @ service: used to mark and configure the service layer component.

(3). @ Controller: used to mark components of the configuration control layer (such as actions in struts ).

(4). @ Repository: used to mark and configure the data access layer component, that is, the common Dao layer bean object.

Note: For bean objects configured using spring annotation, the default name of bean reference is the first letter of the name to be annotated in lowercase. You can also specify the name, for example: @ Service ("userdao").

11. Automatic Spring assembly:

Automatic Assembly means that you do not need to manually explicitly configure the dependency between Java Beans, but instead allow spring to automatically inject appropriate objects to the target objects based on certain rules. In spring, @ autowire and @ resource are often used for automatic assembly.

(1). @ autowire: automatic assembly is performed based on the object data type by default, as shown in figure

@Autowireprivate UserDao userDao;

The Spring framework automatically injects an object of the userdao type at runtime.

(2). @ Resource: automatically assemble by name or ID by default. It is assembled by type only when no matching name or ID is found, for example:

@Resource(name=”userDao”)private UsreDao userDao;

The Spring framework injects an object with the configuration name or ID "userdao" at runtime.

Note: Both @ autowire and @ resource can be written in either a field or a set method.

12. Automatic spring scanning:

The spring automatic scanning mechanism means that after we use the annotation-based Spring configuration method, the spring configuration file only needs to register the annotation processor without explicitly configuring the bean, when spring is running, it automatically scans all beans in the class path under the given conditions, injects and assembles them according to annotations, and initializes them.

Automatic scanning is easy. You only need to add the following content to the spring configuration file:

<Context: component-scan base-package = "Name of the package to be automatically scanned">

At runtime, spring can automatically scan, inject, assemble, and initialize all beans with spring annotations added to the specified package.

Note: For annotation-based Spring configuration, automatic assembly and automatic scanning are closely linked to work together, and the context namespace must be introduced.

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.