【Spring】02:注解开发

第二章:Spring注解开发


OVERVIEW

  • 第二章:Spring注解开发
      • 一、Spring配置数据源
        • 1.配置数据源
        • 2.Spring配置数据源
        • 3.Spring配置数据源抽取
      • 二、Spring注解开发
        • 1.Spring原始注解
        • 2.Spring新注解
        • 3.代码演示
          • (1)xml配置
          • (2)注解配置
      • 三、Spring整合Junit
        • 1.Spring集成Junit
        • 2.Spring集成Junit步骤

一、Spring配置数据源

1.配置数据源

  1. 导入数据源坐标数据库驱动坐标
  2. 创建数据源对象
  3. 设置数据源的基本连接参数
  4. 使用数据源获取连接资源
  5. 归还连接资源

【Spring】02:注解开发_第1张图片

package test;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DataSourceTest {
    @Test
    //测试手动创建c3p0数据源
    public void test1() throws PropertyVetoException, SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("20001201");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

    @Test
    //测试手动创建Druid数据源
    public void test2() throws PropertyVetoException, SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("20001201");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

    @Test
    //测试手动创建Druid数据源(加载properties配置文件)
    public void test3() throws PropertyVetoException, SQLException {
        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String dirver = rb.getString("jdbc.driver");
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String password = rb.getString("jdbc.password");
        //创建数据源对象 设置连接参数
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dirver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test
jdbc.username = root
jdbc.password = root

【Spring】02:注解开发_第2张图片

2.Spring配置数据源

针对上述的数据源配置中,可将DataSource的创建权交给Spring容器去完成:

【Spring】02:注解开发_第3张图片

package test;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DataSourceTest {
    @Test
    //测试Spring容器创建Druid数据源(加载properties配置文件)
    public void test2() throws PropertyVetoException, SQLException {
        //读取配置文件
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = app.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver">property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test">property>
        <property name="user" value="root">property>
        <property name="password" value="20001201">property>
    bean>
beans>

【Spring】02:注解开发_第4张图片

3.Spring配置数据源抽取

applicationContext.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

【Spring】02:注解开发_第5张图片

package test;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DataSourceTest {
    @Test
    //测试Spring容器创建Druid数据源(加载properties配置文件)
    public void test2() throws PropertyVetoException, SQLException {
        //读取配置文件
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = app.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" 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>
beans>

【Spring】02:注解开发_第6张图片

在这里插入图片描述

二、Spring注解开发

Spring是轻代码重配置的框架,配置比较繁重影响开发效率,

注解替代xml配置文件可以简化配置,提高开发效率:

1.Spring原始注解

Spring原始注解主要是替代中的配置,

【Spring】02:注解开发_第7张图片

package com.itcast.service.Impl;

import com.itcast.dao.UserDao;
import com.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//
@Component("userService")
public class UserServiceImpl implements UserService {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    //
    //@Autowired //按照数据类型从Spring容器中进行匹配
    //@Qualifier("userDao") //按照id值从容器中进行匹配 主要结合@Autowired同时使用
    @Resource(name = "userDao") //等价于@Autowired+@Qualifier
    private UserDao userDao;

    public void save() {
        System.out.println(driver);
        System.out.println(url);
        userDao.save();
    }
}

【Spring】02:注解开发_第8张图片

2.Spring新注解

原始注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:

  1. 非自定义的Bean的配置:
  2. 加载properties文件的配置:
  3. 组件扫描的配置:
  4. 引入其他文件:

【Spring】02:注解开发_第9张图片

3.代码演示

(1)xml配置

【Spring】02:注解开发_第10张图片

package com.itcast.dao.Impl;

import com.itcast.dao.UserDao;

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("saving running....");
    }
}
package com.itcast.service.Impl;

import com.itcast.dao.UserDao;
import com.itcast.service.UserService;

public class UserServiceImpl implements UserService {
    //通过set方法进行依赖注入
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void save() {
        userDao.save();
    }
}
package com.itcast.web;

import com.itcast.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserController {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }
}

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" 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>

    
    <bean id="userDao" class="com.itcast.dao.Impl.UserDaoImpl">bean>
    <bean id="userService" class="com.itcast.service.Impl.UserServiceImpl">
        <property name="userDao" ref="userDao">property>
    bean>
beans>

【Spring】02:注解开发_第11张图片

(2)注解配置

【Spring】02:注解开发_第12张图片

package com.itcast.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

//负责数据源的相关配置
//加载外部的properties文件
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
    /*
        
        
        
        
    */
    //jdbc.properties在Spring容器中,所以可以进行注入
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Bean("dataSource") //Spring会将当前方法的返回值以指定名称存储到Spring容器中
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
package com.itcast.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

//标志该类是Spring和核心配置类
@Configuration
//扫描外部的properties文件
@ComponentScan("com.itcast")
//
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {

}
package com.itcast.dao.Impl;

import com.itcast.dao.UserDao;
import org.springframework.stereotype.Component;

//依赖注入
@Component("userDao")
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("saving running....");
    }
}
package com.itcast.service.Impl;

import com.itcast.dao.UserDao;
import com.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//
@Component("userService")
public class UserServiceImpl implements UserService {
    //依赖注入
    //@Autowired //按照数据类型从Spring容器中进行匹配
    //@Qualifier("userDao") //按照id值从容器中进行匹配 主要结合@Autowired同时使用
    @Resource(name = "userDao") //等价于@Autowired+@Qualifier
    private UserDao userDao;

    public void save() {
        userDao.save();
    }
}
package com.itcast.web;

import com.itcast.config.SpringConfiguration;
import com.itcast.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class UserController {
    public static void main(String[] args) throws SQLException {
        ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        UserService userService = app.getBean(UserService.class);
        userService.save();
        DataSource dataSource = app.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

【Spring】02:注解开发_第13张图片

三、Spring整合Junit

1.Spring集成Junit

在测试类中,每个测试方法都有以下两行代码用于获取容器:

ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = app.getBean(UserService.class);
  1. 可以让SpringJunit负责创建Spring容器,但是需要为Spring指明配置文件的名称,
  2. 让需要进行测试的Bean直接在测试类中进行注入。

2.Spring集成Junit步骤

  1. 导入Spring集成Junit的坐标
  2. 使用@Runwith注解替换原来的运行期
  3. 使用@ContextConfiguration指定配置文件 or 配置类
  4. 使用@Autowired注入需要测试的对象
  5. 创建测试方法进行测试
<dependency>
	<groupId>org.springframeworkgroupId>
	<artifactId>spring-testartifactId>
	<version>5.0.5.RELEASEversion>
dependency>
package com.itcast.test;

import com.itcast.config.SpringConfiguration;
import com.itcast.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.SQLException;

@RunWith(SpringJUnit4ClassRunner.class)
@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());
    }
}

【Spring】02:注解开发_第14张图片

你可能感兴趣的