Spring创建bean的几种方法

通过类的静态方法得到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>

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页