BeanFactory接口是Spring容器的核心接口,负责:实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。
Spring为我们提供了许多易用的BeanFactory实现,XmlBeanFactory就是常用的一个,该实现将以XML方式描述组成应用的对象及对象间的依赖关系。XmlBeanFactory类将持有此XML配置元数据,并用它来构建一个完全可配置的系统或应用。
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
Object bean = bf.getBean(IUserService.class);
System.out.println(bean);
接口中定义的方法
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
BeanFactory接口是Spring的核心接口。功能非常复杂,这个时候如果我们想要编写一些比较复杂点儿的逻辑就会触及到其他一些不必要的接口,不好实现。这时候使用FactoryBean就比较方便了。FactoryBean以Bean结尾是个Bean对象,不是工厂。接口中定义的方法如下:
public interface FactoryBean<T> {
/**
* 返回对象的实例
*/
T getObject() throws Exception;
/**
* 返回对象的类型
*/
Class<?> getObjectType();
/**
* 是否是单例
*/
boolean isSingleton();
}
接口和实现类
public interface IUserService {
public void doSome();
}
public class UserServiceImpl implements IUserService {
public UserServiceImpl(){
System.out.println("--被实例化了--");
}
@Override
public void doSome() {
System.out.println("UserServiceImpl 。。。 被执行了");
}
}
自定义FactoryBean
public class MyFactoryBean implements FactoryBean<IUserService>{
@Override
public IUserService getObject() throws Exception {
System.out.println("--IUserService实例化之前---");
IUserService service = new UserServiceImpl();
System.out.println("--IUserService实例化后---");
return service;
}
@Override
public Class<?> getObjectType() {
return IUserService.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myFactoryBean" class="com.dpb.factorybean.MyFactoryBean"/>
beans>
测试–通过类型获取
@Test
public void test1() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
Object bean = bf.getBean(IUserService.class);
System.out.println(bean);
}
输出结果
--IUserService实例化之前---
--被实例化了--
--IUserService实例化后---
com.dpb.service.UserServiceImpl@5315b42e
测试–通过id获取
@Test
public void test1() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
Object bean = bf.getBean("myFactoryBean");
System.out.println(bean);
}
输出结果
--IUserService实例化之前---
--被实例化了--
--IUserService实例化后---
com.dpb.service.UserServiceImpl@783e6358
如果想要获取FactoryBean对象 id前加 &就可以
@Test
public void test1() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
Object bean = bf.getBean("&myFactoryBean");
System.out.println(bean);
}
输出结果
com.dpb.factorybean.MyFactoryBean@3b81a1bc
通过FactoryBean创建一个代理类来增强目标类,我们来看下效果
接口和实现类
public interface IUserService {
public void doSome();
}
public class UserServiceImpl implements IUserService {
public UserServiceImpl(){
System.out.println("--被实例化了--");
}
@Override
public void doSome() {
System.out.println("UserServiceImpl 。。。 被执行了");
}
}
自定义FactoryBean
public class MyFactoryBean implements FactoryBean,InitializingBean,DisposableBean{
private Object proxyObject;
private Object target;
private String interfaceName;
@Override
public Object getObject() throws Exception {
return proxyObject;
}
@Override
public Class<?> getObjectType() {
return proxyObject.getClass()==null?Object.class:proxyObject.getClass();
}
@Override
public boolean isSingleton() {
return true;
}
/**
* MyFactoryBean 对象销毁的回调方法
* @throws Exception
*/
@Override
public void destroy() throws Exception {
System.out.println("destroy ....");
}
/**
* MyFactoryBean 对象实例化的方法
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("---afterPropertiesSet---");
proxyObject = Proxy.newProxyInstance(
this.getClass().getClassLoader()
, new Class[]{Class.forName(interfaceName)}
, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("----代理方法执行开始----");
Object obj = method.invoke(target, args);
System.out.println("----代理方法执行结束----");
return obj;
}
});
}
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;
}
}
配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.dpb.service.UserServiceImpl" id="userServiceImpl"/>
<bean id="myFactoryBean" class="com.dpb.factorybean.MyFactoryBean">
<property name="interfaceName" value="com.dpb.service.IUserService"/>
<property name="target" ref="userServiceImpl"/>
bean>
beans>
测试
@Test
public void test1() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
IUserService bean = (IUserService) ac.getBean("myFactoryBean");
System.out.println("****************");
bean.doSome();
System.out.println();
}
输出结果:
--被实例化了--
---afterPropertiesSet---
****************
----代理方法执行开始----
UserServiceImpl 。。。 被执行了
----代理方法执行结束----
小结:通过输出结果我们可以看到通过FactoryBean接口我们也可以实现BeanFactory中某些接口提供的功能,而且会更加的灵活一些。
Spring在整合mybatis框架的时候提供的SqlSessionFactoryBean就是FactoryBean的很好的实现。
<bean class="org.mybatis.spring.SqlSessionFactoryBean"
id="sqlSessionFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-cfg.xml"/>
<property name="typeAliasesPackage" value="com.sxt.model"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
Spring会调用SqlSessionFactoryBean这个实现了FactoryBean的工厂Bean 同时加载dataSource,Mapper文件的路径,对sqlSessionFactory进行初始化。
源代码比较多就不一一贴出来。到了这儿可以自行跟踪下源代码。
核心方法
@Override
public void afterPropertiesSet() throws Exception {
// 省略
this.sqlSessionFactory = buildSqlSessionFactory();
}
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
// 省略
return this.sqlSessionFactoryBuilder.build(configuration);
}
/**
* {@inheritDoc}
*/
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
/**
* {@inheritDoc}
*/
@Override
public Class<? extends SqlSessionFactory> getObjectType() {
return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSingleton() {
return true;
}
maven坐标:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.2version>
dependency>