Java/Spring/IoC Factory Beans
Содержание
Accessing Factory Beans
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
//spring.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="messageDigest" class="MessageDigestFactoryBean">
<property name="algorithmName">
<value>SHA1</value>
</property>
</bean>
</beans>
//////////////////////////////////////////////////////////////////////////////
import java.security.MessageDigest;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
public class MessageDigestFactoryBean implements FactoryBean, InitializingBean {
private String algorithmName = "MD5";
private MessageDigest messageDigest = null;
public Object getObject() throws Exception {
return messageDigest;
}
public Class getObjectType() {
return MessageDigest.class;
}
public boolean isSingleton() {
return true;
}
public void afterPropertiesSet() throws Exception {
messageDigest = MessageDigest.getInstance(algorithmName);
}
public void setAlgorithmName(String algorithmName) {
this.algorithmName = algorithmName;
}
}
//////////////////////////////////////////////////////////////////////////////
import java.security.MessageDigest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class AccessingFactoryBeans {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/spring.xml"));
MessageDigest digest = (MessageDigest) factory
.getBean("messageDigest");
MessageDigestFactoryBean factoryBean = (MessageDigestFactoryBean) factory
.getBean("&messageDigest");
}
}
Custom Editor Example
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File:custom.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean name="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.regex.Pattern">
<bean class="PatternPropertyEditor"/>
</entry>
</map>
</property>
</bean>
<bean id="exampleBean" class="CustomEditorExample">
<property name="searchPattern">
<value>(dog|fox)</value>
</property>
<property name="textToSearch">
<value>The quick brown fox jumped over the lazy dog.</value>
</property>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
import java.beans.PropertyEditorSupport;
import java.util.regex.Pattern;
public class PatternPropertyEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
Pattern pattern = Pattern.rupile(text);
setValue(pattern);
}
}
///////////////////////////////////////////////////////////////////////////////////////
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class CustomEditorExample {
private Pattern searchPattern;
private String textToSearch;
public static void main(String[] args) {
ConfigurableListableBeanFactory factory = new XmlBeanFactory(
new FileSystemResource("build/custom.xml"));
CustomEditorConfigurer config = (CustomEditorConfigurer) factory
.getBean("customEditorConfigurer");
config.postProcessBeanFactory(factory);
CustomEditorExample bean = (CustomEditorExample) factory
.getBean("exampleBean");
System.out.println(bean.getMatchCount());
}
public void setSearchPattern(Pattern searchPattern) {
this.searchPattern = searchPattern;
}
public void setTextToSearch(String textToSearch) {
this.textToSearch = textToSearch;
}
public int getMatchCount() {
Matcher m = searchPattern.matcher(textToSearch);
int count = 0;
while (m.find()) {
count++;
}
return count;
}
}
Hierarchical Bean Factory Usage
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: beans.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- hierarchical bean factories -->
<bean id="target1" class="SimpleTarget">
<property name="val">
<ref bean="injectBeanParent"/>
</property>
</bean>
<bean id="target2" class="SimpleTarget">
<property name="val">
<ref local="injectBean"/>
</property>
</bean>
<bean id="target3" class="SimpleTarget">
<property name="val">
<ref parent="injectBean"/>
</property>
</bean>
<bean id="injectBean" class="java.lang.String">
<constructor-arg>
<value>Bean In Child</value>
</constructor-arg>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
//File: parent.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="injectBean" class="java.lang.String">
<constructor-arg>
<value>Bean In Parent</value>
</constructor-arg>
</bean>
<bean id="injectBeanParent" class="java.lang.String">
<constructor-arg>
<value>Bean In Parent</value>
</constructor-arg>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
public class SimpleTarget {
private String val;
public void setVal(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class HierarchicalBeanFactoryUsage {
public static void main(String[] args) {
BeanFactory parent = new XmlBeanFactory(new FileSystemResource(
"build/parent.xml"));
BeanFactory child = new XmlBeanFactory(new FileSystemResource(
"build/beans.xml"), parent);
SimpleTarget target1 = (SimpleTarget) child.getBean("target1");
SimpleTarget target2 = (SimpleTarget) child.getBean("target2");
SimpleTarget target3 = (SimpleTarget) child.getBean("target3");
System.out.println(target1.getVal());
System.out.println(target2.getVal());
System.out.println(target3.getVal());
}
}
Logging Bean Example
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: logging.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="loggingBean" class="LoggingBean"/>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
import org.apache.rumons.logging.Log;
import org.apache.rumons.logging.LogFactory;
import org.springframework.beans.factory.BeanNameAware;
public class LoggingBean implements BeanNameAware {
private static final Log log = LogFactory.getLog(LoggingBean.class);
private String beanName = null;
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public void someOperation() {
if(log.isInfoEnabled()) {
log.info("Bean [" + beanName + "] - someOperation()");
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class LoggingBeanExample {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/logging.xml"));
LoggingBean bean = (LoggingBean)factory.getBean("loggingBean");
bean.someOperation();
}
}
Message Digest Example
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: factory.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="shaDigest" class="MessageDigestFactoryBean">
<property name="algorithmName">
<value>SHA1</value>
</property>
</bean>
<bean id="defaultDigest" class="MessageDigestFactoryBean"/>
<bean id="digester" class="MessageDigester">
<property name="digest1">
<ref local="shaDigest"/>
</property>
<property name="digest2">
<ref local="defaultDigest"/>
</property>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
import java.security.MessageDigest;
import sun.misc.BASE64Encoder;
public class MessageDigester {
private MessageDigest digest1 = null;
private MessageDigest digest2 = null;
public void setDigest1(MessageDigest digest1) {
this.digest1 = digest1;
}
public void setDigest2(MessageDigest digest2) {
this.digest2 = digest2;
}
public void digest(String msg) {
System.out.println("Using digest1");
digest(msg, digest1);
System.out.println("Using digest2");
digest(msg, digest2);
}
private void digest(String msg, MessageDigest digest) {
System.out.println("Using alogrithm: " + digest.getAlgorithm());
digest.reset();
byte[] bytes = msg.getBytes();
byte[] out = digest.digest(bytes);
BASE64Encoder enc = new BASE64Encoder();
System.out.println(enc.encode(out));
}
}
///////////////////////////////////////////////////////////////////////////////////////
import java.security.MessageDigest;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
public class MessageDigestFactoryBean implements FactoryBean, InitializingBean {
private String algorithmName = "MD5";
private MessageDigest messageDigest = null;
public Object getObject() throws Exception {
return messageDigest;
}
public Class getObjectType() {
return MessageDigest.class;
}
public boolean isSingleton() {
return true;
}
public void afterPropertiesSet() throws Exception {
messageDigest = MessageDigest.getInstance(algorithmName);
}
public void setAlgorithmName(String algorithmName) {
this.algorithmName = algorithmName;
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class MessageDigestExample {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/factory.xml"));
MessageDigester digester = (MessageDigester) factory
.getBean("digester");
digester.digest("Hello World!");
}
}
Method Replacement Example
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: replacement.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="methodReplacer" class="FormatMessageReplacer"/>
<bean id="replacementTarget" class="ReplacementTarget">
<replaced-method name="formatMessage" replacer="methodReplacer">
<arg-type>String</arg-type>
</replaced-method>
</bean>
<bean id="standardTarget" class="ReplacementTarget"/>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
public class ReplacementTarget {
public String formatMessage(String msg) {
return "<h1>" + msg + "</h1>";
}
public String formatMessage(Object msg) {
return "<h1>" + msg + "</h1>";
}
public void foo() {
}
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class FormatMessageReplacer implements MethodReplacer {
public Object reimplement(Object target, Method method, Object[] args)
throws Throwable {
if (isFormatMessageMethod(method)) {
String msg = (String) args[0];
return "<h2>" + msg + "</h2>";
} else {
throw new IllegalArgumentException("Unable to reimplement method "
+ method.getName());
}
}
private boolean isFormatMessageMethod(Method method) {
// check correct number of params
if (method.getParameterTypes().length != 1) {
return false;
}
// check method name
if (!("formatMessage".equals(method.getName()))) {
return false;
}
// check return type
if (method.getReturnType() != String.class) {
return false;
}
// check parameter type is correct
if (method.getParameterTypes()[0] != String.class) {
return false;
}
return true;
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StopWatch;
public class MethodReplacementExample {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/replacement.xml"));
ReplacementTarget replacementTarget = (ReplacementTarget) factory
.getBean("replacementTarget");
ReplacementTarget standardTarget = (ReplacementTarget) factory
.getBean("standardTarget");
displayInfo(replacementTarget);
displayInfo(standardTarget);
}
private static void displayInfo(ReplacementTarget target) {
System.out.println(target.formatMessage("Hello World!"));
StopWatch stopWatch = new StopWatch();
stopWatch.start("perfTest");
for (int x = 0; x < 1000000; x++) {
String out = target.formatMessage("foo");
}
stopWatch.stop();
System.out.println("1000000 invocations took: "
+ stopWatch.getTotalTimeMillis() + " ms");
}
}
Property Editor Bean
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: builtin.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="builtInSample" class="PropertyEditorBean">
<property name="class">
<value>java.lang.String</value>
</property>
<property name="file">
<value>c:/test.txt</value>
</property>
<property name="locale">
<value> en-GB </value>
</property>
<property name="url">
<value>http://www.springframework.org</value>
</property>
<property name="properties">
<value>
name=foo
age=19
</value>
</property>
<property name="strings">
<value>rob,jan,rod,jurgen,alef</value>
</property>
<property name="bytes">
<value>Hello World</value>
</property>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
import java.io.File;
import java.net.URL;
import java.util.Locale;
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class PropertyEditorBean {
private Class cls;
private File file;
private URL url;
private Locale locale;
private Properties properties;
private String[] strings;
private byte[] bytes;
public void setClass(Class cls) {
System.out.println("Setting class: " + cls.getName());
this.cls = cls;
}
public void setFile(File file) {
System.out.println("Setting file: " + file.getName());
this.file = file;
}
public void setLocale(Locale locale) {
System.out.println("Setting locale: " + locale.getDisplayName());
this.locale = locale;
}
public void setProperties(Properties properties) {
System.out.println("Loaded " + properties.size() + " properties");
this.properties = properties;
}
public void setStrings(String[] strings) {
System.out.println("Loaded " + strings.length + " Strings");
this.strings = strings;
}
public void setUrl(URL url) {
System.out.println("Setting URL: " + url.toExternalForm());
this.url = url;
}
public void setBytes(byte[] bytes) {
System.out.println("Adding " + bytes.length + " bytes");
this.bytes = bytes;
}
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/builtin.xml"));
PropertyEditorBean bean = (PropertyEditorBean) factory
.getBean("builtInSample");
}
}