Spring -- 全注解下的IoC(2)

  自定义第三方的Bean

    1.maven 添加DBCP 和 MySQL 的依赖

    

      <!-- dbcp 连接池依赖 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.4.0</version>
        </dependency>

        <!-- mysql jdbc 依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>

    2. dbcp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/weather2
username=root
password=250019
initialSize=10
maxActivite=30
maxIdle=10
maxWait=1000
removeAbandoned=ture
removeAbandonedTimeout=180

    3.AppConfig

      使用 @Bean 手动注入一个名字为dataSource的Bean到IoC容器中

package com.com.example.demo3;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;


@Configuration
@ComponentScan
public class AppConfig {
    private static final String configFile = "dbcp.properties";

    @Bean(name = "dataSource")
    public DataSource getDataSource(){
        Properties properties = new Properties();
        DataSource dataSource = null;

        try {
            properties.load(AppConfig.class.getClassLoader().getResourceAsStream(configFile));
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }
}

 

posted @ 2018-12-06 16:12  Weeeeew  阅读(125)  评论(0编辑  收藏  举报