Archive for the ‘disposablebean’ tag

Loaded on more than view.properties SpringMVC development issues

June 17, 2010
use SpringMVC the development process, if you use a mixed view of way, and using the ResourceBundleViewResolver way. The only way to read the default classpath following view.properties (of course, be other properties files, but also with Locale, the basename of the properties can be configured).
For a project to develop if more than one person situation, we have to modify this file is clearly not practical, the best way to have each module below view.properties, in the system whether to automatically start loading, which can increase the concurrent development of the efficiency and reduce the cost of the project synthesis.
simply looked ResourceBundleViewResolver, which would like to start from this class to achieve a ViewResolver, so as to achieve automatic load, the following is achieved:
/ / $ Id: AutoResourceBundleViewResolver. java 2010-6-17 morning 11:26:23
package com.jtv.walllee.common.extend;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.NoSuchBeanDefini tionException;
import org.springframework.beans.factory.support. Properti esBeanDefinitionReader;
import org.springframework.context.ConfigurableApplicatio nContext;
import org.springframework.core.Ordered;
import org.springframework . core.io.Resource;
import org.springframework.core.io.support.PathMatchingRe sourcePatternResolver;
import org.springframework.core.io.support.ResourcePatter nResolver ;
import org.springframework.web.context.support.GenericWeb ApplicationContext;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractCachi ngViewResolver;
/ **
*
*

* @ author Wall.Lee (xiaoshan2242@gmail.com)
* /
public class AutoResourceBundleViewResolver extends AbstractCachingViewResolver implements Ordered, DisposableBean {
private int order = Integer.MAX_VALUE; / / default: same as non-Ordered
private String scanFileName; / / scan view filename
private String defaultParentView;
private Locale [] localesToInitialize;
/ * Locale -> BeanFactory * /
private final Map localeCache = new HashMap ();
/ * List of ResourceBundle -> BeanFactory * /
private final Map resourceCache = new HashMap ();
public void setOrder (int order) {
this.order = order;
}

public int getOrder () {
return this.order;
}
public void setDefaultParentView (String defaultParentView) {
< br /> this.defaultParentView = defaultParentView;
}
public void setLocalesToInitialize (Locale [] localesToInitialize) {
this.localesToInitialize = localesToInitialize;
}
protected void initApplicationContext () throws BeansException {
if (this.localesToInitialize! = null) {

for (int i = 0; i initFactory (this.localesToInitialize [i]);
}
}
}
protected View loadView (String viewName, Locale locale) throws Exception {
BeanFactory factory = initFactory (locale) ;
try {
return (View) factory.getBean (viewName, View.class);
}

catch (NoSuchBeanDefinitionException ex) {
return null;
}
}
protected synchronized BeanFactory initFactory (Locale locale) throws BeansException {
if (isCache ()) {
BeanFactory cachedFactory = (BeanFactory) this.localeCache.get (locale);

if (cachedFactory! = null) {
return cachedFactory;
}
}
/ / Build list of ResourceBundle references for Locale.
Resource [] resouces = getAllResources ();
if (isCache ()) {
BeanFactory cachedFactory = ( BeanFactory) this.resourceCache.get (resouces);
if (cachedFactory! = null) {
this.localeCache.put (locale, cachedFactory);
return cachedFactory;
}
}
/ / Create child ApplicationContext for views.
GenericWebApplicationContext factory = new GenericWebApplicationContext ();
factory.setParent (getApplicationContext ());
factory.setServletContext (getServletContext ());
/ / Load bean definitions from resource bundle.
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader (factory);
reader.setDefaultParentBean (this.defaultParentView);
reader.loadBeanDefinitions (resouces);
factory.refresh ();
if (isCache ()) {
this.localeCache.put ( locale, factory);
this.resourceCache.put (resouces, factory);
}
return factory;
}
@ SuppressWarnings (“unchecked”)
public void destroy () throws BeansException {
for (Iterator it = this.resourceCache . values ??(). iterator (); it.hasNext ();) {
ConfigurableApplicationContext factory = (ConfigurableApplicationContext) it.next ();
factory.close () ;
}
this.localeCache.clear ();
this.resourceCache.clear ();
}
/ **
* need to search for file system resources
* @ return
* @ throws IOException
* /
private Resource [] getAllResources () {
if (scanFileName == null| “”. equals (scanFileName )) {
scanFileName = “view.properties”;
}
String filePattern = “classpath *:/**/*” scanFileName;
ResourcePatternResolver resoler = new PathMatchingResourcePatternResolver ();
try {
return resoler.getResources (filePattern);
} catch (IOException e) {
e.printStackTrace ();
}
return new Resource [0];

}
public String getScanFileName () {
return scanFileName;
}
public void setScanFileName (String scanFileName) {
this.scanFileName = scanFileName;
}
}
– Configuration < br />
in the *- servlet.xml configuration



which identifies the need to scan documents scanFileName , Note: the default scan path is the classpath.

Posted: January 6th, 2012
at 11:19am by admin

Tagged with


Categories: Uncategorized

Comments: No comments


spring2.5 annotation-driven (B) @ PostConstruct @ PreDestroy

July 19, 2010
Spring container Bean is a life-cycle, Spring allows Bean and Bean in the initialization is complete destruction of the former to perform specific operations, you can only achieve InitializingBean / DisposableBean interface to customize the initialization / destruction before the method of operation, you can also specify element init-method/destroy-method property after initialization / destruction of the operation method is called before
JSR-250 is initialized / destroyed before the specified method defines two comment categories, namely @ PostConstruct and @ PreDestroy, this method can only be applied on the two notes. Marked with @ PostConstruct annotation method is called after the class is instantiated, the method marked @ PreDestroy destroyed in the class is called before we know whether it is through the realization of InitializingBean / DisposableBean interface, or through the init- elements method / destroy-method attribute can be configured for the Bean can only specify an initialization / destruction methods. But the use of annotation @ PostConstruct and @ PreDestroy but you can specify more than one initialization / destruction methods, or those who have been marked @ PostConstruct @ PreDestroy annotated method will be initialized / destroyed is executed, generally designated one, to avoid confusion < br />
package com.baobaotao;
import javax.annotation.Resource;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
publicclass Boss {
@ Resource
private Car car;
@ Resource (name = “office”)
private Office office;
@ PostConstruct
publicvoid postConstruct1 () {
System.out.println (“postConstruct1″);
}
@ PreDestroy
publicvoid preDestroy1 () {

System.out.println (“preDestroy1″);
}

}
test class code
package com.baobaotao;
import org.springframework.context.support.ClassPathXmlAp plicationContext;
publicclass AnnoIoCTest {
publicstaticvoid main (String [] args) {
String [] locations = {“beans.xml”};
ClassPathXmlApplicationContext ctx =

new ClassPathXmlApplicationContext (locations);
Boss boss = (Boss) ctx.getBean (“boss”);
System.out.println (boss);

ctx.destroy (); / / close the Spring container, in order to trigger the execution of methods of destruction Bean
}
}
At this time, you will see marked @ PostConstruct of postConstruct1 () method will start in the Spring container to create Boss Bean is triggered when executed, and marked with @ PreDestroy comments preDestroy1 () method will be destroyed before the closure of the Spring container Boss Bean is triggered when the execution.
use simplify configuration
Spring 2.1 adds a new context of Schema namespace, the namespace of the annotation-driven, the introduction of property file , load-time weaver into other functions provide a convenient configuration. We know that comment alone will not do anything, it only provides metadata information. For metadata information that really works, must deal with the metadata of the processor to work.
We previously described AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor is to deal with these annotations metadata processor. However, a Spring Bean configuration file to define these seemed more clumsy. Spring provides us a convenient way to register these BeanPostProcessor, which is . Consider the following configuration:

xmlns: xsi =” http://www.w3.org/2001/XMLSchema-instance “
xmlns: context =” http://www.springframework.org/schema/context “
xsi: schemaLocation =” http://www.springframework.org/schema/beans
http: / / www.springframework.org / schema / beans / spring-bean s-2.5.xsd
http://www.springframework.org/schema/context
http : / / www.springframework.org / schema / context / spring-co ntext-2.5.xsd “>





< br />


the Spring container to implicitly registered AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor and equiredAnnotationBeanPostProcessor four BeanPostProcessor.
in the configuration file using the context namespace, you must element in the context namespace declarations.

Posted: January 6th, 2012
at 11:18am by admin

Tagged with


Categories: Uncategorized

Comments: No comments


some of the concepts in the spring IOC

September 28, 2010
java2010-09-28 13:06:23 0 comments Word Count: Spring container supports the use of the XML bean factory assembly class

XmlBeanFactory: a simple BeanFactory, it uses java.io.InputStream
ClassPathXmlApplicationContext: an application context, it is loaded from the classpath, context definition file
FileSystemXmlApplicationContext : an application context, it is loaded from the file system context file
XmlWebApplicationContext: Spring-based Web applications up and down the file, file it down from the Web application context definition file loaded.
2: Basic format




3: prototype and single-instance:
default is a single instance, if you use the prototype, you can use the following form

class = “”
singleton = “false” />

4: instantiated and destroyed
can use the init-method, the Bean is instantiated when Hou was immediately called, and you can set destory -method, remove from the window in the Bean before calling. Spring also provides two interfaces to achieve the same functionality: InitializingBean and DisposableBean.
InitializingBean provides a method afterPropertiesSet (), after setting all properties used in the call, DisposableBean provides a destroy -method for the destruction of Bean

class = “”

init-method = “” destroy-method =”"/>

5: Set method by injecting dependencies
Bean usually there are some simple types of properties, to set the basic types of properties

class = “”>





6: References to other Bean
elements used to set the properties to other Bean . Sub-elements with Let achieve this.

class = “”>





7: Internal Bean
do not use another method of assembly Bean reference element is embedded in a element,


class = “”>



8: assembling a collection
Spring support collection type
XML type
java.awt.List, arrays
java.awt.Set


java.awt.Map
java.awt.Properties

class = “”>

barl




9: Assembly Map
In Spring
elements can be used to assemble a collection java.util.Map.

class = “”>


bar1



< / entry>



10: assembly Properties
java.util.Properties Spring is finally assembled in a collection of classes, to assemble it using elements, and
to use are very similar, they are the largest The difference is that the value can only be String type.
bar1
bar2



11: set null
If you need to explicitly set the value of an attribute to NULL, just use element on the line
12: an alternative to injection (constructor injection of dependencies)
sometimes attribute values ??can only be set once created, can not be changed later, Sometimes all the properties exposed by the set method is not possible. By constructor to set the value of the property instead.
use the Set injection, we injected element value of the property. Constructor is the same, but under the by element element to specify the instance of the bean needed parameters. One of these two methods in different places is: no name attribute, and have a name this property.


42





< br />

in the use of the constructor, the parameters will have a lot of uncertainty, there are two ways to deal with the uncertainty of the constructor: serial number and type element has an optional index attribute, the constructor can be used to specify the order, you can also use the type attribute to specify the exact type of each parameters, it can specify each parameter type.


http : / / www.manning.com


http://www.springinaction.com


The following is a type of form

< br />
http://www.manning.com


http://www.springinaction.com



If two parameters are the same data type (such as is String), then you can only use the index property
13 : automatic assembly:
Spring to get automatic assembly, automatic assembly as long as the need to set the autowire attribute .
There are four types of automatic assembly byName, byType, constructor, autodetect
14
distributed configuration in most cases, the Bean in a assembly system, you can assign it to a different file, you can configure the assembly file in the Bean Data Source.
15 custom property editor
getAsText (): Returns a string attribute value that
setAsText (String value): the string passed to it is assigned to Bean properties
custom editor includes ClassEditor, CustomDateEditor, FileEditor, LocalEdito r, StringArrayPropertyEditor, StringTrimmerEditor.

Posted: January 6th, 2012
at 11:18am by admin

Tagged with


Categories: Uncategorized

Comments: No comments