通过类的静态方法得到conn
public class ConnectionFactory {
static public Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
}
}
<bean id="conn" class="com.mj.obj.ConnectionFactory" factory-method="getConnection"/>
先实例化一个类,然后调用实例方法创建bean
public class ConnectionFactory {
private String driver;
private String url;
private String username;
private String password;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public Connection getConnection() throws Exception {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
<bean id="connFactory" class="com.mj.obj.ConnectionFactory">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="password" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
</bean>
<bean id="conn" factory-bean="connFactory" factory-method="getConnection"/>
继承FactoryBean,直接拿到Factory产生的实例
public class ConnectionFactoryBean implements FactoryBean<Connection> {
private String driver;
private String url;
private String username;
private String password;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Connection getObject() throws Exception {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
@Override
public Class<?> getObjectType() {
return Connection.class;
}
}
<bean id="conn" class="com.mj.obj.ConnectionFactoryBean">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="password" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
</bean>
版权声明:本文为weixin_43625164原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。