spring中的新注解





spring整合Junit分析

1、应用程序的入口
      main方法
2、junit单元测试中,没有main方法也能执行
    junit集成了一个main方法
    该方法就会判断当前测试类中哪些方法有 @Test注解
    junit就让有Test注解的方法执行
3、junit不会管我们是否采用spring框架
    在执行测试方法时,junit根本不知道我们是不是使用了spring框架
    所以也就不会为我们读取配置文件/配置类创建spring核心容器
4、由以上三点可知
    当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入






pom.xml

<?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>com.dym</groupId><artifactId>day02_eesy_04account_annoioc_withoutxml</artifactId><version>1.0-SNAPSHOT</version><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.6</source><target>1.6</target></configuration></plugin></plugins></build><packaging>jar</packaging><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.4</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies></project>

Account.java

package com.itheima.domain;import java.io.Serializable;/*** 账户的实体类*/
public class Account implements Serializable {private Integer id;private String name;private Float 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 Float getMoney() {return money;}public void setMoney(Float money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}

IAccountDao.java

package com.itheima.dao;import com.itheima.domain.Account;import java.util.List;/*** 账户的持久层接口*/
public interface IAccountDao {/*** 查询所有* @return*/List<Account> findAllAccount();/*** 查询一个* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 删除* @param acccountId*/void deleteAccount(Integer acccountId);
}

AccountDaoImpl.java

package com.itheima.dao.impl;import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;import java.util.List;/*** 账户的持久层实现类*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {@Autowiredprivate QueryRunner runner;@Overridepublic List<Account> findAllAccount() {try{return runner.query("select * from account",new BeanListHandler<Account>(Account.class));}catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic Account findAccountById(Integer accountId) {try{return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic void saveAccount(Account account) {try{runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());}catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic void updateAccount(Account account) {try{runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic void deleteAccount(Integer accountId) {try{runner.update("delete from account where id=?",accountId);}catch (Exception e) {throw new RuntimeException(e);}}
}

IAccountService.java

package com.itheima.service;import com.itheima.domain.Account;import java.util.List;/*** 账户的业务层接口*/
public interface IAccountService {/*** 查询所有* @return*/List<Account> findAllAccount();/*** 查询一个* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 删除* @param acccountId*/void deleteAccount(Integer acccountId);
}

AccountServiceImpl.java

package com.itheima.service.impl;import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** 账户的业务层实现类*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService{@Autowiredprivate IAccountDao accountDao;@Overridepublic List<Account> findAllAccount() {return accountDao.findAllAccount();}@Overridepublic Account findAccountById(Integer accountId) {return accountDao.findAccountById(accountId);}@Overridepublic void saveAccount(Account account) {accountDao.saveAccount(account);}@Overridepublic void updateAccount(Account account) {accountDao.updateAccount(account);}@Overridepublic void deleteAccount(Integer acccountId) {accountDao.deleteAccount(acccountId);}
}

jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=root

JdbcConfig.java

package config;import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;import javax.sql.DataSource;/*** 和spring连接数据库相关的配置类*/
public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;/*** 用于创建一个QueryRunner对象* @param dataSource* @return*/@Bean(name="runner")@Scope("prototype")public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){return new QueryRunner(dataSource);}/*** 创建数据源对象* @return*/@Bean(name="ds2")public DataSource createDataSource(){try {ComboPooledDataSource ds = new ComboPooledDataSource();ds.setDriverClass(driver);ds.setJdbcUrl(url);ds.setUser(username);ds.setPassword(password);return ds;}catch (Exception e){throw new RuntimeException(e);}}@Bean(name="ds1")public DataSource createDataSource1(){try {ComboPooledDataSource ds = new ComboPooledDataSource();ds.setDriverClass(driver);ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");ds.setUser(username);ds.setPassword(password);return ds;}catch (Exception e){throw new RuntimeException(e);}}
}

SpringConfiguration.java

package config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;/*** 该类是一个配置类,它的作用和bean.xml是一样的*/
// 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {}

测试queryrunner是否单例

QueryRunnerTest.java

package com.itheima.test;import config.SpringConfiguration;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;/*** 测试queryrunner是否单例*/
public class QueryRunnerTest {@Testpublic  void  testQueryRunner(){//1.获取容器ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);//2.获取queryRunner对象QueryRunner runner = ac.getBean("runner",QueryRunner.class);QueryRunner runner1 = ac.getBean("runner",QueryRunner.class);System.out.println(runner == runner1);}
}

AccountServiceTest.java

package com.itheima.test;import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;
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 java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {@Autowiredprivate IAccountService as = null;@Testpublic void testFindAll() {//3.执行方法List<Account> accounts = as.findAllAccount();for(Account account : accounts){System.out.println(account);}}@Testpublic void testFindOne() {//3.执行方法Account account = as.findAccountById(1);System.out.println(account);}@Testpublic void testSave() {Account account = new Account();account.setName("test anno");account.setMoney(12345f);//3.执行方法as.saveAccount(account);}@Testpublic void testUpdate() {//3.执行方法Account account = as.findAccountById(4);account.setMoney(23456f);as.updateAccount(account);}@Testpublic void testDelete() {//3.执行方法as.deleteAccount(4);}
}

Spring的新注解——Configuration、ComponentScan、Bean、Import、PropertySource || spring整合Junit分析相关推荐

  1. Spring-学习笔记06【Spring的新注解】

    Java后端 学习路线 笔记汇总表[黑马程序员] Spring-学习笔记01[Spring框架简介][day01] Spring-学习笔记02[程序间耦合] Spring-学习笔记03[Spring的 ...

  2. 【Spring】新注解

    新注解 注解 释意 @Configuration 作用:指定当前类是一个配置类 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写 ...

  3. JAVAEE框架之Spring新注解

    五.Spring5 新注解 ​ 新的注解有用,为后面的SpringBoot可以打一个基础,因为到SpringBoot的课程, 多了很多注解.这时候,先了解一部分. 5.1 @Configuration ...

  4. Spring-学习笔记04【Spring的常用注解】

    Java后端 学习路线 笔记汇总表[黑马程序员] Spring-学习笔记01[Spring框架简介][day01] Spring-学习笔记02[程序间耦合] Spring-学习笔记03[Spring的 ...

  5. Spring深入理解之ComponentScan___@ComponentScan 详解

    Spring深入理解之ComponentScan 一.概述 ComponentScan顾名思义包扫描,底层其实就可以通过递归算法+反射将其装载成bean来实现的,实在开发过程中,Spring已经帮我们 ...

  6. @Configuration 和 @Bean

    1. @Bean: 1.1 定义 从定义可以看出,@Bean只能用于注解方法和注解的定义. @Target({ElementType.METHOD, ElementType.ANNOTATION_TY ...

  7. spring中的注解配置

    步骤: 1.为主配置文件引入新的命名空间(引入约束) 2.开启使用注解代替配置文件 在spring配置文件applicationContext中配置 <!-- 指定扫描com.lsz.sprin ...

  8. Spring高级之注解@PropertySource详解(超详细)

    定义/作用 @PropertySource注解用于指定资源文件读取的位置,它不仅能读取properties文件,也能读取xml文件,并且通过YAML解析器,配合自定义PropertySourceFac ...

  9. 【Spring4.0】基于注解的方式Bean配置

    一.注解的作用 组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件. 二.特定的注解 @Component: 基 ...

最新文章

  1. 云计算究竟是什么呢?“汇新杯”新兴科技成果专项赛之——云计算
  2. android线程及线程池
  3. 从FCN到DeepLab
  4. python bootstrap-fileinput示例_bootstrapfileinput实现文件自动上传
  5. SAP UI5 WebIDE里使用Mock数据的工作原理介绍
  6. 使用HTML5+CSS3制作圆角内发光按钮----示例
  7. 一维条形码***技术(Badbarcode)
  8. canvas填充规则
  9. 独立磁盘冗余阵列:RAID
  10. win10 dns异常上不了网如何解决
  11. @enableautoconfiguration注解作用_Spring Boot最核心的27个干货注解,你了解多少?
  12. StarGate(星际之门)观看指南
  13. 免费ppt模板在哪下载?轻松get免费ppt模板下载网站
  14. unity 实现PPT动画效果切换图片
  15. Photoshop 抠图方法
  16. HTML标签关系——双标签和单标签,标签的嵌套与并列
  17. .Net Framework 、.Net 、 .NET Standard的概念与区别
  18. 高等数学Mathematica实验题——费马素数猜想(Fn=2^(2^n)+1为素数)的证伪(Verification of Fermat's Prime Number Function)
  19. 万网空间 php伪静态,百度云虚拟主机zblogphp在Nginx环境下设置伪静态规则,极为重要...
  20. 【流媒体服务器Mediasoup】多人音视频架构、流媒体的比较、mediasoup介绍 (一)

热门文章

  1. git 入门教程之协同开发
  2. 洛谷2505 [HAOI2012]道路(最短路计数)
  3. leaflet的入门开发(一)
  4. java构造函数使用方法总结
  5. [Window] .MUS 0x80070422 Error
  6. Dell服务器使用集成RAID卡
  7. jdbc mysql 自动重连_JDBC实现Mysql自动重连机制的方法详解
  8. JSTL解析——001
  9. NEO智能合约黑盒测试框架
  10. vue-router使用next()跳转到指定路径时会无限循环