Java/Spring/IoC Construct
Constructor Confusion
/*
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>
<!-- ctor confusion -->
<bean id="constructorConfusion" class="ConstructorConfusion">
<constructor-arg type="int">
<value>90</value>
</constructor-arg>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class ConstructorConfusion {
private String someValue;
public ConstructorConfusion(String someValue) {
System.out.println("ConstructorConfusion(String) called");
this.someValue = someValue;
}
public ConstructorConfusion(int someValue) {
System.out.println("ConstructorConfusion(int) called");
this.someValue = "Number: " + Integer.toString(someValue);
}
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/beans.xml"));
ConstructorConfusion cc = (ConstructorConfusion) factory.getBean("constructorConfusion");
System.out.println(cc);
}
public String toString() {
return someValue;
}
}
Default Creator Example
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: dpac.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="autoBean" class="AutoBean"/>
<bean id="otherBean" class="OtherBean"/>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
public class AutoBean {
public void foo() {
System.out.println("foo()");
}
}
///////////////////////////////////////////////////////////////////////////////////////
public class OtherBean {
public void foo() {
System.out.println("foo()");
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class DefaultCreatorExample {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"build/dpac.xml");
AutoBean autoBean = (AutoBean)ctx.getBean("autoBean");
OtherBean otherBean = (OtherBean)ctx.getBean("otherBean");
autoBean.foo();
System.out.println(AopUtils.isAopProxy(autoBean));
otherBean.foo();
System.out.println(AopUtils.isAopProxy(otherBean));
}
}