Spring学习(二)

1. Spring配置数据源

1.1 数据源(连接池)作用

  • 数据源(连接池)是提高程序新能是如何实现的
  • 事先实例化数据源,初始化部分连接资源
  • 使用连接资源时从数据源中获取
  • 使用完毕后将连接资源归还给数据源

常见的数据源(连接池):DBCP、C3P0、BoneCP 、Druid等

1.2 数据源的开发步骤

  1. 导入数据源的坐标和数据库驱动坐标
<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

    </dependencies>
  1. 创建数据源对象
  2. 设置数据源的基本连接数据
  3. 使用数据源获取连接资源和归还连接资源

具体实例:

 @Test
    //测试手动创建c3p0数据库
    public void test1() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
    
 @Test
    //测试手动创建druid数据库
    public void test2() throws Exception{
        DruidDataSource dataSource= new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();

    }

加载properties配置文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/
jdbc.username=root
jdbc.password=root
@Test
    //测试手动创建c3p0数据库(加载配置文件)
    public void test3() throws Exception {
        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driver = rb.getString("jdbc.driver");
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String passsword = rb.getString("jdbc.password");

        //创建数据源对象,设置连接参数
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(passsword);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

1.3 Spring配置数据源

  1. 配置spring-context坐标

    <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
    
  2. 创建Spring config

    <bean id="dataSouce" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    
  3. 测试

    @Test
        //测试Spring容器产生数据源对象
        public void test4() throws Exception {
            ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
            DataSource dataSource = app.getBean(DataSource.class);
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
            connection.close();
        }
    

1.4 抽取jdbc配置文件

applictionContext.xml加载jdbc.properties配置文件获得连接信息

首先,需要引入context命名空间和约束路径

  • 命名空间:xmlns:context="http://www.springframework.org/schema/context"
  • 约束路径:http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

在applicationContext.xml中加载:

<!--加载外部properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <bean id="dataSouce" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

2. Spring注解开发

2.1 Spring原始注解

Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。

Spring原始注解主要替代的配置
在这里插入图片描述
注意:

使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法

<!--配置组件扫描-->
    <context:component-scan base-package="com.itcainiao"></context:component-scan>

2.2 Spring新注解

  • 非自定义的Bean的配置:<bean>
  • 加载properties文件的配置:<contextproperty-placeholder>
  • 组件扫描的配置:<contextcomponent-scan>
  • 引入其他文件<import>
    在这里插入图片描述

3. Spring整合Junit

3.1 原始junit测试Spring的问题

在测试类中,每个测试方法都有以下两行代码:

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml")
UserService userService = app.getBean(UserService.class);

这两行代码的作用:获取容器,如果不写的话,直接会提示空指针异常,所以又不能轻易删掉。

3.2 解决思路

  • 让SpringJunit负责创建spring容器,但是需要将配置文件的名称告诉他
  • 将需要进行测试Bean直接在测试类中进行注入

3.3 Spring集成junit步骤

  1. 导入spring集成junit的坐标
<dependencies>
	<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
	<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9.RELEASE</version>
  	</dependency>
</dependencies>
  1. 使用@Runwith注解替换原来的运行期
  2. 使用@ContextConfiguration指定配置文件或配置类
  3. 使用@Autowired注入需要测试的对象
  4. 创建测试方法进行测试
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")

@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSource dataSource;


    @Test
    public void test1() throws SQLException {
        userService.save();
        System.out.println(dataSource.getConnection());
    }

}

4. Spring集成web环境

4.1 ApplicationContext应用上下文获取方式

应用上下文对象是通过new ClasspathXmlApplicationContext(spring配置文件)方式获取的,但是每次从容器中获得Bean时都要编写new ClasspathXmlApplictaionContext(Spring配置文件),这样的弊端是配置文件加载多次,应用上下文对象创建多次。

在Web项目中,可以使用ServletContextLinstener监听Web应用的启动,我们可以在web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文applicationContext对象了。

4.2 Spring提供获取应用上下文的工具

Spring提供了一个监听器ConTextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到Servlet Context域中,提供了一个客户端工具WebApplicationContextUtils提供使用者获得上下文对象。

要用需做:

  1. 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
<!-- 在pom.xml导入spring-web坐标-->
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
<!--全局初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  1. 使用WebApplictaionContextUtils获得应用上下文对象ApplicationContext
public class UserServlet<get> extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        ServletContext servletContext = req.getServletContext();
//        ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
       // ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值