自学内容网 自学内容网

Spring学习笔记(二)

十三、 Spring整合JDBC实现CRUD

(一)、整合思路分析

        Spring提供了ioc容器,管理jdbc操作数据库的过程中需要的数据库连接对象,同时Spring提供了整合jdbc操作数据库的工具类JdbcDaoSupport 和模板工具 JdbcTemplate,在JdbcTemplate中提供了大量的操作数据库的方式供用户使用。所以我们只需要获取模板工具类然后调用方法就可以完成Jdbc的操作了。

(二)、创建maven工程

         添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SpringFrameWorkProject03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.18</version>
        </dependency>

        <!--导入jdbc模块依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>

</project>

(三)、实体类Account

package com.jn.entity;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

(四)、持久层AccountDao

package com.jn.dao;

import com.jn.entity.Account;

import java.util.List;

public interface AccountDao {
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id); 
    public Account findById(Integer id);
    
    public Integer getTotallRecords();
    
    public List<Account> findAll();
}

(五)、实现类AccountDaoImp

package com.jn.dao.impl;

import com.jn.dao.AccountDao;
import com.jn.entity.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountDaiImpl implements AccountDao {
    
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void save(Account account) {
        String sql = "insert into account(name,money) values(?,?)";
        jdbcTemplate.update(sql,account.getName(),account.getMoney());
    }

    @Override
    public void update(Account account) {
        String sql = "update account set name=?,money=? where id=?";
        jdbcTemplate.update(sql,account.getName(),account.getMoney(),account.getId());
    }

    @Override
    public void delete(Integer id) {
        String sql = "delete from account where id=?";
        jdbcTemplate.update(sql,id);
    }

    @Override
    public Account findById(Integer id) {
        String sql = "select * from account where id=?";
        Account account = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Account>(Account.class),id);
        return account;
    }

    @Override
    public Integer getTotallRecords() {
        int count = jdbcTemplate.queryForObject("select count(*) from account",Integer.class);
        return count;
    }

    @Override
    public List<Account> findAll() {
        String sql = "select * from account";
        List<Account> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }
}

(六)、业务层AccountService

package com.jn.service;

import com.jn.entity.Account;

import java.util.List;

public interface AccountService{
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
    public Account findById(Integer id);

    public Integer getTotallRecords();

    public List<Account> findAll();
}

(七)、实现类AccountServiceImpl

package com.jn.service.impl;

import com.jn.dao.AccountDao;
import com.jn.entity.Account;
import com.jn.service.AccountService;

import java.util.List;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void save(Account account) {
        this.accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        this.accountDao.update(account);
    }

    @Override
    public void delete(Integer id) {
        this.accountDao.delete(id);
    }

    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Override
    public Integer getTotallRecords() {
        return accountDao.getTotallRecords();
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}

(八)、配置容器管理对象

<?xml version="1.0" encoding="UTF-8"?>
<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.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
     </bean>

<!--配置JdbcTempalte对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

<!--AccountDaoImpl-->
    <bean id="accountDao" class="com.jn.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

<!--AccountServiceImpl-->
    <bean id="accountService" class="com.jn.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>

(九)测试

package com.jn;

import com.jn.dao.AccountDao;
import com.jn.entity.Account;
import com.jn.service.AccountService;
import com.jn.service.impl.AccountServiceImpl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class JdbcTemplateTest {

    //save测试
    @Test
    public void save(){
        //获取
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) context.getBean("accountService");
        Account account = new Account();
        account.setName("王思梦");
        account.setMoney(999999.99);
        accountService.save(account);
        System.out.println("Save Successful");
    }

    //update测试
    @Test
    public void update(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) context.getBean("accountService");
        Account account = new Account();
        account.setId(2);
        account.setName("铁头");
        account.setMoney(66666.66);
        accountService.update(account);
        System.out.println("Update Successful");

    }

    //delete测试
    @Test
    public void delete(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) context.getBean("accountService");
        accountService.delete(3);
        System.out.println("Delete Successful");
    }

    //findById测试
    @Test
    public void findById(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) context.getBean("accountService");
        Account account = accountService.findById(1);
        System.out.println(account);
    }

    //findAll测试
    @Test
    public void findAll(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) context.getBean("accountService");

        List<Account> list = accountService.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }

    //getTotallRecords测试
    @Test
    public void getTotallRecords(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) context.getBean("accountService");
        int count = accountService.getTotallRecords();
        System.out.println(count);
    }
    

}

 项目整体目录结构

十四、Spring常用注解

(一)、 注解和 XML 的选择问题

        学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

        关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯 , 所以这两种配置方式我们都需要掌 握。

注解的优势: 配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。

xml的优势: 修改时,不用改源码。不涉及重新编译和部署。

(二)、创建对象的注解:

@Component        @Repository        @Service        @Controller

注解说明
@Component使用在类上用于实例化Bean
@Controller使用在web层类上用于实例化Bean
@Service使用在service层类上用于实例化Bean
@Repository使用在dao层类上用于实例化Bean

 注意:

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

1.接口层UserDao 

        使用@Component或@Repository标识UserDaoImpl需要Spring进行实例化。

package com.jn.dao;

public interface UserDao {
    public void save();
}

2.实现类UserDaoImpl

        使用@Component或@Service标识UserServiceImpl需要Spring进行实例化

package com.jn.dao.impl;

import com.jn.dao.UserDao;
import org.springframework.stereotype.Repository;


/*
使用注解来进行组件的注入
 value属性可以省略,默认是类名首字母小写
 组件的id默认是类名首字母小写

 此处component为万能的注解,在进行测试的时候能正常运行,看表格应用在dao层类里面的实例化Bean所以用到@Repository
 */
//@Component(value = "userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println("Saving Running");
    }
}

 3.组件扫描applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://www.springframework.org/schema/context/spring-context.xsd">



    <!--注解的组件扫描-->
    <!--base-packeg可以不用精确到 com.jn.dao.impl,只要在父类包下面都会被扫描到-->
    <context:component-scan base-package="com.jn"></context:component-scan>
</beans>

4.测试 

package com.jn;

import com.jn.dao.UserDao;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationTest {

    //测试component和Repository注解
    @Test
    public void testRepository(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) context.getBean("userDao");
        userDao.save();

    }
}

(三)、注入数据的注解

@Value        @Resource        @Autowrited        @Qualifier

注解说明
@Value注入普通属性
@Autowired自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到就报错
@Qualifier结合@Autowired一起使用用于根据名称进行依赖注入
@Resource相当于@Autowired+@Qualifier,按照名称进行注入

1.@Value

 1.1修改UserDao
package com.jn.dao.impl;

import com.jn.dao.UserDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;


/*
使用注解来进行组件的注入
 value属性可以省略,默认是类名首字母小写
 组件的id默认是类名首字母小写

 此处component为万能的注解,在进行测试的时候能正常运行,看表格应用在dao层类里面的实例化Bean所以用到@Repository
 */
//@Component(value = "userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Value("注入了一条字符串")
    private String str;
    @Override
    public void save() {
        System.out.println(str);
        System.out.println("Saving Running");
    }
}
1.2测试 
    //测试Value注解
    @Test
    public void testValue(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) context.getBean("userDao");
        userDao.save();

    }

 2.@Autowired、@Autowired+@Qulifier、@Resource

2.1业务层UserService
 2.2添加依赖
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.2</version>
</dependency>
2.3实现类UserServiceImpl
package com.jn.service.impl;

import com.jn.dao.UserDao;
import com.jn.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//@Component("userService")万能注解,此处使用service的专用注解@Service
@Service("userService")
public class UserServiceImpl implements UserService {

    //在业务层Userservice实现类中,需要引入数据层UserDao

    //在此处添加注解,表示自动装配
    //@Autowired
    //@Qualifier("userDao")
    @Resource(name = "userDao")
    private UserDao userDao;
    @Override
    public void save() {
        userDao.save();
    }
}
2.4测试 
    //测试Resource注解
    @Test
    public void testResource(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.save();
    }

(四)、改变作用范围的注解

注解

说明

@Scope

标注Bean的作用范围,scope取值singleton prototype request session globalsession

 1.添加作用域

package com.jn.service.impl;

import com.jn.dao.UserDao;
import com.jn.service.UserService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//@Component("userService")万能注解,此处使用service的专用注解@Service
@Scope("prototype")//测试Bean的作用域默认为单例模式
@Service("userService")
public class UserServiceImpl implements UserService {

    //在业务层Userservice实现类中,需要引入数据层UserDao

    //在此处添加注解,表示自动装配
    //@Autowired
    //@Qualifier("userDao")
    @Resource(name = "userDao")
    private UserDao userDao;
    @Override
    public void save() {
        userDao.save();
    }
}

2.测试

    //测试Scope作用域
    @Test
    public void testScope(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        UserService userService1 = (UserService) context.getBean("userService");
        System.out.println(userService);
        System.out.println(userService1);
    }

十五、 Spring基于注解的IoC案例

(一)、maven工程添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SringFrameWorkProject05</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.18</version>
        </dependency>

        <!--导入jdbc模块依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>

</project>

(二)、注解配置管理资源

1. 实体类User 

package com.jn.entity;

import java.io.Serializable;
import java.util.Date;

public class User  implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    private String gender;
    private Date birthday;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public User(String name, Integer age, String gender, Date birthday) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

2.持久层UserDao

package com.jn.dao;

import com.jn.entity.User;

public interface UserDao {
    public void addUser(User user);
}

3.实现类UserDaoImpl

package com.jn.dao.impl;

import com.jn.dao.UserDao;
import com.jn.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaiImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void addUser(User user) {
        String sql="insert into users(name,age,gender,birthday) values(?,?,?,?)";
        jdbcTemplate.update(sql,user.getName(),user.getAge(),user.getGender(),user.getBirthday());
    }
}

4.业务层UserService

package com.jn.service;

import com.jn.entity.User;

public interface UserService {
    public void addUser(User user);
}

5.实现类UserServiceImpl

package com.jn.service.impl;

import com.jn.dao.UserDao;
import com.jn.entity.User;
import com.jn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }
}

(三)、dbconfig.properties配置

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdatabase
jdbc.username=root
jdbc.password=123456

 (四)、配置文件开启对注解支持

<?xml version="1.0" encoding="UTF-8"?>
<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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描指定的基础包以寻找和注册组件 -->
    <context:component-scan base-package="com.jn"/>

    <!-- 加载 properties 文件的配置 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

<!--    &lt;!&ndash;配置数据源&ndash;&gt;-->
<!--    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
<!--        <property name="driverClass" value="com.mysql.jdbc.Driver"/>-->
<!--        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatisdatabase"/>-->
<!--        <property name="user" value="root"/>-->
<!--        <property name="password" value="123456"/>-->
<!--    </bean>-->

    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>

</beans>

(五)、测试完成注解IOC操作

package com.jn;

import com.jn.entity.User;
import com.jn.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;

public class annotationTest {
    //测试关于注解开发的IOC案例
    @Test
    public void test1()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        User user = new User("小明", 12, "男", new Date());
        userService.addUser(user);
        System.out.println("添加成功");
    }
}

项目整体目录结构

十六、Spring 的纯注解配置

(一)、注解说明

@Configuration,@ComponentScan, @Import,@Bean,@PropertySource

注解

说明

@Configuration

用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解

@ComponentScan

用于指定 Spring在初始化容器时要扫描的包。 作用和在 Spring 的 xml 配置文件中的 <context:component-scan base-package="com.offcn"/>一样

@Bean

使用在方法上,标注将该方法的返回值存储到 Spring容器中

@PropertySource

用于加载xxx.properties 文件中的配置

@Import

用于导入其他配置类

(二)、纯注解配置类SpringConfig 

package com.jn.config;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration  //指定当前类是一个配置类,取代了applicationContext.xml
@ComponentScan("com.jn")    //指定Spring在初始化容器时要扫描的包,取代了<context:component-scan base-package="com.jn"/>
//@Import(JdbcTemplate.class)导入了其他类的配置,跟xml里面的import的导入一样,此处需要用到JdbcTemplate还要另外配置
@PropertySource("classpath:dbconfig.properties")    //加载 properties 文件的配置
public class SpringConfig {

    @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(name="dataSource")        //将方法的返回值存入到IOC容器里面,并指定bean的id
    public ComboPooledDataSource getResource() throws Exception{
        ComboPooledDataSource resource = new ComboPooledDataSource();
        resource.setDriverClass(driver);
        resource.setJdbcUrl(url);
        resource.setUser(username);
        resource.setPassword(password);
        return resource;
    }

    //形式参数,从容器里面获取对象
    @Bean(name="jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
}

(三)、测试

1.先删除applicationContext.xml

 2.编写测试类

    //测试纯注解开发
    @Test
    public void test2()
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = (UserService) context.getBean("userService");
        User user = new User("吴邪", 33, "男", new Date());
        userService.addUser(user);
        System.out.println("添加成功");
    }

3.测试结果 

十七、Spring 整合 Junit

(一)、IOC测试类中的问题和解决思路

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

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");

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

(二)、整合Junit 配置步骤

1 添加技术依赖

<!--spring整合Juint的依赖-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.18</version>
</dependency>

2 使用@RunWith 注解替换原有运行器

@RunWith(SpringJUnit4ClassRunner.class)

3 使用@ContextConfiguration 指定 Spring 配置文件的位置

//@ContextConfiguration(value = "classpath:applicationContext.xml") 加入有核心配置文件applicationContext.xml的注解配置

//配置注解配置类
@ContextConfiguration(classes = SpringConfig.class)

4 使用@Autowired 给测试类中的变量注入数据

    //使用Spring进行Juint整合的测试
    @Autowired
    private UserService userService;
    @Test
    public void test3()
    {
        userService.addUser(new User("王月半", 35, "男", new Date()));
        System.out.println("添加成功");
    }

 5.测试结果


原文地址:https://blog.csdn.net/m0_67226963/article/details/143530622

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!