Spring 2.0 core technology and best practices Day 2

Source: Internet
Author: User

Component is a common bean (used for reuse)

Manage beans using IOC containers
1. Function reuse, class reuse, and Component Reuse (using interfaces ?)
2. The control (responsible for creating configuration components) is reversed and is transferred from the application to the IOC container.
The IOC container can be "assembled" and requires an "injection" mechanism for the component to be injected to another component.
Dependency injection: separates component configuration and usage, and the IOC container is responsible for managing the life cycle of components.
3. Dependency injection: constructor injection, attribute injection, and interface injection.
4. Spring IoC containers include xmlbeanfactory and applicationcontext (an instance class that implements the beanfactory interface)
Xmlbeanfactory requires an XML and a resource object.
Eg.1 beanfactory factory = new xmlbeanfactory (New filesystemresource ("C: // test // config. xml "));
2. beanfactory factory = new xmlbeanfactory (New classpathresource ("config. xml "));
5. How the container parses XML (that is, the bean initialization process)
1. The Container instantiate a bean according to the bean definition in the XML configuration file and input necessary constructor parameters.
2. The container uses dependency injection to set bean Attributes Based on the xml configuration file.
13 if bean defines the init-method, call this method to perform initialization.

6. Assemble the bean (that is, correctly configure Each bean node in the XML configuration file, and write the bean to XML)
<Bean id = "examplebean"
Class = "example. chapter3.examplebean"
Init-method = "init">
<Property name = "size" value = "10"/>
<Property name = "size" ref = "..."/> reference type
</Bean>

Injection types
Package example. Chapter3;

Import java. util. List;

Public class listbean {

Public void setchildren (list children ){}

Public void setprices (list <float> prices ){
For (float F: Prices ){
System. Out. println (f );
}
}

Public void setfibonacci (INT [] Fibonacci ){
For (int n: Fibonacci ){
System. Out. println (N );
}
}

}

<Bean id = "listbean" class = "example. chapter3.listbean">
<! -- Inject common list -->
<Property name = "children">
<List>
<Value> A string </value>
<Ref bean = "basicbean"/>
</List>
</Property>
<! -- Inject a strongly typed list <float> -->
<Property name = "Prices">
<List>
<Value> 12.54 </value>
<Value> 82 </value>
<Value> 27.9 </value>
</List>
</Property>
<! -- Inject int [] array -->
<Property name = "maid">
<List>
<Value> 1 </value>
<Value> 1 </value>
<Value> 2 </value>
<Value> 3 </value>
<Value> 5 </value>
</List>
</Property>
</Bean>

<! -- Configure setbean and inject set -->

<Bean id = "setbean" class = "example. chapter3.setbean">
<Property name = "Cups">
<Set>
<Value> spring </value>
<Value> hibernate </value>
<Value> hibernate </value>
<Ref bean = "listbean"/>
</Set>
</Property>
</Bean>

<! -- Configure mapbean and inject map -->

<Bean id = "mapbean" class = "example. chapter3.mapbean">
<Property name = "weekday">
<Map>
<! -- Use string as the key -->
<Entry key = "Monday">
<Value> do something </value>
</Entry>
<Entry key = "Tuesday">
<Ref bean = "setbean"/>
</Entry>
<! -- Use bean as the key -->
<Entry key-ref = "basicbean" value = "Basic"/>
<Entry key-ref = "listbean" value-ref = "setbean"/>
</Map>
</Property>
</Bean>

<! -- Configure propbean and inject properties -->

<Bean id = "propbean" class = "example. chapter3.propbean">
<Property name = "env">
<Props>
<Prop key = "target"> 1.5 </prop>
<Prop key = "encoding"> UTF-8 </prop>
<Prop key = "debug"> On </prop>
</Props>
</Property>
</Bean>

<! -- Configure constructorbean and inject it from the constructor -->

<Bean id = "constructorbean" class = "example. chapter3.constructorbean">
<Constructor-Arg value = "100" type = "codeph" text = "codeph"/>
<Constructor-Arg value = "200" type = "codeph" text = "codeph"/>
</Bean>

Inject Resource

<Bean id = "resourcebean" class = "example. chapter3.resourcebean">
<Property name = "urlresource" value = "http://www.javaeedev.com/"/>
<Property name = "classpathresource" value = "classpath: config. xml"/>
<Property name = "fileresource" value = "C:/Windows/notepad. EXE"/>
</Bean>

Import java. Io. ioexception;
Import org. springframework. Core. Io. resource;
Public class resourcebean {
Public void seturlresource (resource Resource) throws ioexception {
System. Out. println (resource. geturl ());
}
Public void setclasspathresource (resource Resource) throws ioexception {
System. Out. println (resource. GetFile ());
}
Public void setfileresource (resource Resource) throws ioexception {
System. Out. println (resource. GetFile ());
}

}

<Bean id = "resourcebean" class = "example. chapter3.resourcebean">
<Property name = "urlresource" value = "http://www.javaeedev.com/"/>
<Property name = "classpathresource" value = "classpath: config. xml"/>
<Property name = "fileresource" value = "C:/Windows/notepad. EXE"/>
</Bean>
1. urlresource
Urlresource encapsulates java.net. url, which can be used to access any objects that can be obtained through URLs, such as files, HTTP objects, and FTP objects. All URLs are represented by a standard string. These standard prefixes can identify different URL types, including file: access to the file system path, http: Resources accessed through HTTP, FTP: resources accessed through FTP.

The urlresource object can be explicitly created using the urlresource constructor in Java code. But more is implicitly created by calling the API function with the string parameter indicating the path. In the latter case, the propertyeditor of the JavaBeans determines the type of resource to be created. If this string contains some well-known prefixes, such as classpath:, it will create a corresponding serialized resource. However, if the prefix cannot be identified, it is assumed to be a standard URL string and then a urlresource is created.
2. classpathresource
This class identifies the resources obtained from classpath. It uses the class loader of the thread context, a given class loader, or a given class used to load resources.

If the resources in the class path exist in the file system, the implementation of this resource will provide functions similar to Java. Io. File. If the resource exists in a jar package that has not been unlocked (unlocked by the servlet engine or other environments), these resource implementations provide functions similar to java.net. URL.

The classpathresource object can be explicitly created using the classpathresource constructor in Java code. But more is implicitly created by calling the API function with the string parameter indicating the path. In the latter case, the propertyeditor of the JavaBeans identifies the classpath: prefix in the string and then creates the classpathresource accordingly.
3. filesystemresource
This is the resource implementation prepared for processing java. Io. File. It can be provided as either a file or a URL.
4. servletcontextresource
This is the resource implementation provided for the servletcontext resource. It is responsible for parsing the relative path in the root directory of the relevant web application.

It always supports stream and URL access. However, java. Io. file access is allowed only when the web application package is unwrapped and the resource is on the physical path of the file system. Whether to unbind and access in the file system, or directly access from the jar package or in other ways, such as dB (which can be imagined) depends only on the servlet container.
5. inputstreamresource
This is the resource implementation prepared for the given inputstream. It is used only when there are no other appropriate resource implementations. Additionally, use bytearrayresource or other file-based resource whenever possible.

Unlike other resource implementations, this is a resource descriptor that has been opened-so the isopen () function returns true. If you want to maintain the resource descriptor or read a stream multiple times, do not use it.
6. bytearrayresource
This is the resource implementation prepared for the given byte array. It constructs a bytearrayinputstream for the given byte array.

It is useful when reading content from any given byte array, because it does not need to be converted into a single inputstreamresource.

Table resource strings

Prefix example
Classpath:
Classpath: COM/MyApp/config. xml
Load from classpath.
 
File:
File:/data/config. xml
Load as a URL from the file system. [A]
 
HTTP:
Http: // myserver/logo.png
Load as a URL.
 
(None)
/Data/config. xml
Judge Based on applicationcontext.
 
 

7bean scope: Singleton (default) each time the getbean () method is called to request a bean, Spring always returns the same bean instance.
Prototype returns a new bean instance each time.
<Bean ID class scope = "prototype">

<! -- Date with the scope of prototype -->

<Bean id = "date"
Class = "Java. util. Date"
Scope = "prototype"
/>
8. Configure the factory Bean: static factory and instance factory.
<! -- Configure a static factory. You can modify the scope of random to view the output result. -->

<Bean id = "random"
Class = "example. chapter3.staticfactorybean"
Factory-method = "createrandom"
Scope = "prototype"
/>
You must use factory-method to specify the static method name.

<! -- Configure the instance factory -->

<Bean id = "instancefactorybean" class = "example. chapter3.instancefactorybean">
<Property name = "format" value = "yyyy-mm-dd hh: mm: SS"/>
</Bean>

<Bean id = "currenttime"
Factory-bean = "instancefactorybean"
Factory-method = "createtime"
/>
To define an instance factory, two beans must be defined respectively.

9. Question: When can attributes be omitted?
Package example. Chapter3;

Import java.net. url;

Public class basicbean {

Private String title;
Public void setusecache (Boolean usecache ){}
Public void setmaxsize (INT size ){}
Public String gettitle () {return title ;}
Public void settitle (String title) {This. Title = title ;}
Public void setfile (URL ){
System. Out. println (URL );
}
}
Can the set attribute be omitted if the name is the same?

What is the role of initializing JNDI?

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.