IDEA版SSM入门到实战(Maven+MyBatis+Spring+SpringMVC) -Spring管理第三方bean

2023-12-14 12:35:48

第一章 Spring管理第三方bean

1.1 Spring管理druid步骤
  • 导入jar包

    <!--导入druid的jar包-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.10</version>
            </dependency>
            <!--导入mysql的jar包-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.37</version>
    <!--            <version>8.0.26</version>-->
            </dependency>
    
  • 编写db.properties配置文件

    #key=value
    db.driverClassName=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://localhost:3306/db220106
    db.username=root
    db.password=root
    
  • 编写applicationContext.xml相关代码

    <!--    加载外部属性文件db.properties-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    
    <!--    装配数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${db.driverClassName}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
    </bean>
    
  • 测试

    @Test
    public void testDruidDataSource() throws Exception{
        //获取容器对象
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("applicationContext_druid.xml");
    
        DruidDataSource dataSource = ioc.getBean("dataSource", DruidDataSource.class);
        System.out.println("dataSource = " + dataSource);
    
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println("connection = " + connection);
    
    }
    

文章来源:https://blog.csdn.net/ZCY5202015/article/details/134983317
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。