FactoryBean
本篇笔记记录与2020年9月,迁移至此分享给需要他的人。
FactoryBean接口:工厂Bean
接口方法:
接口方法 | 描述 |
---|---|
public T getObject() throws Exception { return t; } | 获取bean对象实例 |
public Class<?> getObjectType() { return Xxx.class; } | 反射获取实例的类型 |
public boolean isSingleton() { return true/false; } | 是否单例 |
实例:数据库连接(实例已收录github-Tab-Tan)
工厂Bean代码:(实现FactoryBean接口,实现接口方法)
package factory;
import org.springframework.beans.factory.FactoryBean;
import java.sql.Connection;
import java.sql.DriverManager;
public class MyConnectionFac implements FactoryBean<Connection> {
//数据库连接相关的成员变量
private String url;
private String username;
private String password;
private String driverName;
//获取数据库连接实例
public Connection getObject() throws Exception {
Class.forName(driverName);
return DriverManager.getConnection(url, username, password);
}
//反射获取数据库连接类型
public Class<?> getObjectType() {
return Connection.class;
}
//是否设置为单例
public boolean isSingleton() {
return true;
}
//成员变量的getter、setter方法
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
}
在xml中注册bean并注入成员变量
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--获取小配置文件-->
<context:property-placeholder location="classpath:db/mysql.properties"/>
<!--注册工厂bean,注入成员变量-->
<bean id="conn" class="factory.MyConnectionFac"
p:driverName="${db.driver}"
p:url="${db.url}"
p:username="${db.username}"
p:password="${db.password}"/>
</beans>
测试
package factory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.Connection;
public class MyConnectionTest {
@Test
public void test(){
//创建spring工厂
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取刚刚注册的bean
Connection conn = (Connection) ac.getBean("conn");
//打印验证
System.out.println(conn);
}
}
结果:com.mysql.cj.jdbc.ConnectionImpl@5bfa9431
可以看出获取数据库连接成功了。
探究原理
spring获取conn实例的时候会通过instanceof(FactoryBean)判断这个conn实例是不是实现了工厂Bean接口,实现了FactoryBean返回true后spring调用实现类的**getObject()**方法获取连接对象返回实例。