Resource resource = new FileSystemResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(resource);
ClassPathResource resource = new ClassPathResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(resource);
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml", "applicationContext-part2.xml"}); BeanFactory factory = (BeanFactory) context;
package org.springframework.beans.factory; import org.springframework.beans.BeansException; public interface BeanFactory { String FACTORY_BEAN_PREFIX = "&"; Object getBean(String name) throws BeansException; <T> T getBean(String name, Class<T> requiredType) throws BeansException; <T> T getBean(Class<T> requiredType) throws BeansException; Object getBean(String name, Object... args) throws BeansException; boolean containsBean(String name); boolean isSingleton(String name) throws NoSuchBeanDefinitionException; boolean isPrototype(String name) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException; Class<?> getType(String name) throws NoSuchBeanDefinitionException; String[] getAliases(String name); }
/** * my factory bean<p> * 代理一个类,拦截该类的所有方法,在方法的调用前后进行日志的输出 * @author daniel.zhao * */ public class MyFactoryBean implements FactoryBean<Object>, InitializingBean, DisposableBean { private static final Logger logger = LoggerFactory.getLogger(MyFactoryBean.class); private String interfaceName; private Object target; private Object proxyObj; @Override public void destroy() throws Exception { logger.debug("destroy......"); } @Override public void afterPropertiesSet() throws Exception { proxyObj = Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[] { Class.forName(interfaceName) }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { logger.debug("invoke method......" method.getName()); logger.debug("invoke method before......" System.currentTimeMillis()); Object result = method.invoke(target, args); logger.debug("invoke method after......" System.currentTimeMillis()); return result; } }); logger.debug("afterPropertiesSet......"); } @Override public Object getObject() throws Exception { logger.debug("getObject......"); return proxyObj; } @Override public Class<?> getObjectType() { return proxyObj == null ? Object.class : proxyObj.getClass(); } @Override public boolean isSingleton() { return true; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } public Object getProxyObj() { return proxyObj; } public void setProxyObj(Object proxyObj) { this.proxyObj = proxyObj; } }
<bean id="fbHelloWorldService" class="com.ebao.xxx.MyFactoryBean"> <property name="interfaceName" value="com.ebao.xxx.HelloWorldService" /> <property name="target" ref="helloWorldService" /> </bean>
@RunWith(JUnit4ClassRunner.class) @ContextConfiguration(classes = { MyFactoryBeanConfig.class }) public class MyFactoryBeanTest { @Autowired private ApplicationContext context; /** * 测试验证FactoryBean原理,代理一个servcie在调用其方法的前后,打印日志亦可作其他处理 * 从ApplicationContext中获取自定义的FactoryBean * context.getBean(String beanName) ---> 最终获取到的Object是FactoryBean.getObejct(), * 使用Proxy.newInstance生成service的代理类 */ @Test public void testFactoryBean() { HelloWorldService helloWorldService = (HelloWorldService) context.getBean("fbHelloWorldService"); helloWorldService.getBeanName(); helloWorldService.sayHello(); } }
package org.springframework.beans.factory; public interface FactoryBean<T> { T getObject() throws Exception; Class<?> getObjectType(); boolean isSingleton(); }
package com.baobaotao.factorybean; public class Car { private int maxSpeed ; private String brand ; private double price ; public int getMaxSpeed () { return this . maxSpeed ; } public void setMaxSpeed ( int maxSpeed ) { this . maxSpeed = maxSpeed; } public String getBrand () { return this . brand ; } public void setBrand ( String brand ) { this . brand = brand; } public double getPrice () { return this . price ; } public void setPrice ( double price ) { this . price = price; } }
package com.baobaotao.factorybean; import org.springframework.beans.factory.FactoryBean; public class CarFactoryBean implements FactoryBean<Car> { private String carInfo ; public Car getObject () throws Exception { Car car = new Car () ; String [] infos = carInfo .split ( "," ) ; car.setBrand ( infos [ 0 ]) ; car.setMaxSpeed ( Integer. valueOf ( infos [ 1 ])) ; car.setPrice ( Double. valueOf ( infos [ 2 ])) ; return car; } public Class<Car> getObjectType () { return Car. class ; } public boolean isSingleton () { return false ; } public String getCarInfo () { return this . carInfo ; } // 接受逗号分割符设置属性信息 public void setCarInfo ( String carInfo ) { this . carInfo = carInfo; } }
<bean d="car"class="com.baobaotao.factorybean.CarFactoryBean" P:carInfo="法拉利,400,2000000"/>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="student" class="com.spring.bean.Student"> <property name="name" value="zhangsan" /> </bean> <bean id="school" class="com.spring.bean.School"> </bean> <bean id="factoryBeanPojo" class="com.spring.bean.FactoryBeanPojo"> <property name="type" value="student" /> </bean> </beans>
import org.springframework.beans.factory.FactoryBean; /** * @author 作者 wangbiao * @parameter * @return */ public class FactoryBeanPojo implements FactoryBean{ private String type; @Override public Object getObject() throws Exception { if("student".equals(type)){ return new Student(); }else{ return new School(); } } @Override public Class getObjectType() { return School.class; } @Override public boolean isSingleton() { return true; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
/** * @author 作者 wangbiao * @parameter * @return */ public class School { private String schoolName; private String address; private int studentNumber; public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getStudentNumber() { return studentNumber; } public void setStudentNumber(int studentNumber) { this.studentNumber = studentNumber; } @Override public String toString() { return "School [schoolName=" schoolName ", address=" address ", studentNumber=" studentNumber "]"; } }
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.bean.FactoryBeanPojo; /** * @author 作者 wangbiao * @parameter * @return */ public class FactoryBeanTest { public static void main(String[] args){ String url = "com/spring/config/BeanConfig.xml"; ClassPathXmlApplicationContext cpxa = new ClassPathXmlApplicationContext(url); Object school= cpxa.getBean("factoryBeanPojo"); FactoryBeanPojo factoryBeanPojo= (FactoryBeanPojo) cpxa.getBean("&factoryBeanPojo"); System.out.println(school.getClass().getName()); System.out.println(factoryBeanPojo.getClass().getName()); } }
十一月 16, 2016 10:28:24 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1e8ee5c0: startup date [Wed Nov 16 10:28:24 CST 2016]; root of context hierarchy 十一月 16, 2016 10:28:24 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [com/spring/config/BeanConfig.xml] 十一月 16, 2016 10:28:24 上午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@35b793ee: defining beans [student,school,factoryBeanPojo]; root of factory hierarchy com.spring.bean.Student com.spring.bean.FactoryBeanPojo