文章目录

  • 一、今日内容
  • 二、使用IOC完成改造CRUD
    • a、引入依赖
    • b、创建表
    • c、实体类
  • ==原始方式==
    • d、持久层
    • e、业务层
    • g、测试类
  • ==IOC方式==
    • d、持久层
    • e、业务层
    • f、配置文件
    • g、测试类
  • 三、常用的注解
    • a、注解开发入门流程
    • b、常用注解
      • @Component
      • @Autowired
      • @Resource
        • 两个自动注入的区别
    • 《纯注解开发才用到》
      • @Configuration
      • @ComponentSacn("cn.ahpu")
      • @Import
      • @Bean
      • @Scope("singleton|prototype")
      • 生命周期
      • @Value
      • @PropertySource
      • Demo代码
    • 配置文件分解
      • applicationContext.xml的分解(import 标签和context:property-placeholder)
    • 补:注解扫描配置两个子标签
  • 四、使用注解改造账户CRUD(半xml半注解方式 最常用)
    • a、实体类
    • b、持久层
    • c、业务层
    • d、配置文件
    • e、测试
  • 五、纯注解开发
    • 1. SpringConfiguration.java
    • 2.JDBCConfiguration.java
    • 3.TestCRUD.java
  • 六、spring与junit的整合
    • 1. 引入依赖
    • 2.1配置测试环境-- xml
    • 2.2 配置测试环境-- ann 纯注解方式
    • 3. 测试:从容器可以获取某类型的对象
  • 七、小结

一、今日内容

1、使用IOC完成CRUD
2、基于注解的IOC配置
3、使用注解改造CRUD(半xml半注解)
4、纯注解开发
5、spring与junit的整合

二、使用IOC完成改造CRUD

a、引入依赖

 <dependencies><!--spring核心包 基本--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><!--dbutils--><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.4</version></dependency><!--c3p0数据源--><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><!--单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version></dependency></dependencies>

b、创建表

create database spring331;
use spring331;create table account(id int primary key auto_increment,name varchar(40),money float
) character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);select * from account;

c、实体类

Account.java

package cn.ahpu.domain;/*** @author 寒面银枪* @create 2020-02-07 17:31*/
public class Account {private Integer id;private String name;private Float money;//...@Overridepublic String toString() {return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}';}
}

原始方式

d、持久层

AccountDaoImpl

package cn.ahpu.dao.impl;import cn.ahpu.dao.AccountDao;
import cn.ahpu.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.util.List;/*** @author 寒面银枪* @create 2020-02-07 17:37* 暂时用dbutils操作数据库*/
public class AccountDaoImpl implements AccountDao {//非静态代码块 创建对象时执行   构造方法里写可以达到相同效果{ComboPooledDataSource dataSource = new ComboPooledDataSource();//注入必备的四个参数try {dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring331");dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setUser("root");dataSource.setPassword("root");} catch (PropertyVetoException e) {e.printStackTrace();}queryRunner = new QueryRunner(dataSource);}QueryRunner queryRunner;@Overridepublic List<Account> findAll() {String sql = "select * from Account";try {List<Account> accountList = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));return accountList;} catch (SQLException e) {e.printStackTrace();return null;}}@Overridepublic Account findById(Integer id) {String sql="select * from Account where id=?";try {Account account = queryRunner.query(sql, new BeanHandler<>(Account.class), id);return account;} catch (SQLException e) {e.printStackTrace();}return null;}@Overridepublic void save(Account account) {String sql="insert into account values(null,?,?)";try {queryRunner.update(sql,account.getName(),account.getMoney());} catch (SQLException e) {e.printStackTrace();}}@Overridepublic void update(Account account) {String sql="update account set name=?,money=? where id=?";try {queryRunner.update(sql,account.getName(),account.getMoney(),account.getId());} catch (SQLException e) {e.printStackTrace();}}@Overridepublic void delById(Integer id) {String sql="delete from account where id=?";try {queryRunner.update(sql,id);} catch (SQLException e) {e.printStackTrace();}}
}

AccountDao

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

e、业务层

AccountServiceImpl

public class AccountServiceImpl implements AccountService {AccountDao accountDao = new AccountDaoImpl();@Overridepublic List<Account> findAll() {return accountDao.findAll();}@Overridepublic Account findById(Integer id) {return accountDao.findById(id);}@Overridepublic void save(Account account) {accountDao.save(account);}@Overridepublic void update(Account account) {accountDao.update(account);}@Overridepublic void delById(Integer id) {accountDao.delById(id);}
}

AccountService

public interface AccountService {public List<Account> findAll();public Account findById(Integer id);public void save(Account account);public void update(Account account);public void delById(Integer id);
}

g、测试类

public class TestCRUD {@Testpublic void testFindAll(){//创建service对象AccountService service=new AccountServiceImpl();List<Account> accountList = service.findAll();for (Account account : accountList) {System.out.println(account);}}@Testpublic void testFindById(){//创建service对象AccountService service=new AccountServiceImpl();Account account = service.findById(1);System.out.println(account);}@Testpublic void testSave(){//创建service对象AccountService service=new AccountServiceImpl();Account account=new Account();account.setName("hhh");account.setMoney(999.99f);service.save(account);}@Testpublic void testUpdate(){//创建service对象AccountService service=new AccountServiceImpl();Account account=new Account();account.setName("hhh");account.setMoney(1000f);account.setId(4);service.update(account);}@Testpublic void testDel(){//创建service对象AccountService service=new AccountServiceImpl();service.delById(4);}
}

IOC方式

d、持久层

AccountDaoImpl

public class AccountDaoImpl implements AccountDao {/* //非静态代码块 创建对象时执行   构造方法里写可以达到相同效果{ComboPooledDataSource dataSource = new ComboPooledDataSource();//注入必备的四个参数try {dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring331");dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setUser("root");dataSource.setPassword("root");} catch (PropertyVetoException e) {e.printStackTrace();}queryRunner = new QueryRunner(dataSource);}*///提供set方法 让spring注入QueryRunner queryRunner;public void setQueryRunner(QueryRunner queryRunner) {this.queryRunner = queryRunner;}@Overridepublic List<Account> findAll() {String sql = "select * from Account";try {List<Account> accountList = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));return accountList;} catch (SQLException e) {e.printStackTrace();return null;}}@Overridepublic Account findById(Integer id) {String sql="select * from Account where id=?";try {Account account = queryRunner.query(sql, new BeanHandler<>(Account.class), id);return account;} catch (SQLException e) {e.printStackTrace();}return null;}@Overridepublic void save(Account account) {String sql="insert into account values(null,?,?)";try {queryRunner.update(sql,account.getName(),account.getMoney());} catch (SQLException e) {e.printStackTrace();}}@Overridepublic void update(Account account) {String sql="update account set name=?,money=? where id=?";try {queryRunner.update(sql,account.getName(),account.getMoney(),account.getId());} catch (SQLException e) {e.printStackTrace();}}@Overridepublic void delById(Integer id) {String sql="delete from account where id=?";try {queryRunner.update(sql,id);} catch (SQLException e) {e.printStackTrace();}}
}

e、业务层

AccountServiceImpl

package cn.ahpu.service.impl;import cn.ahpu.dao.AccountDao;
import cn.ahpu.dao.impl.AccountDaoImpl;
import cn.ahpu.domain.Account;
import cn.ahpu.service.AccountService;import java.util.List;/*** @author 寒面银枪* @create 2020-02-07 17:39*/
public class AccountServiceImpl implements AccountService {//提供set方法 让spring注入private AccountDao accountDao;public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}@Overridepublic List<Account> findAll() {return accountDao.findAll();}@Overridepublic Account findById(Integer id) {return accountDao.findById(id);}@Overridepublic void save(Account account) {accountDao.save(account);}@Overridepublic void update(Account account) {accountDao.update(account);}@Overridepublic void delById(Integer id) {accountDao.delById(id);}
}

f、配置文件

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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--创建AccountService:需要AccountDao--><bean id="accountService" class="cn.ahpu.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"></property></bean><!--创建AccountDao:需要queryRunner--><bean id="accountDao" class="cn.ahpu.dao.impl.AccountDaoImpl"><property name="queryRunner" ref="queryRunner"></property></bean><!--创建queryRunner:需要dataSource 构造方法传入的 --><bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"><!--查看QueryRunner源码然后选择合适属性 此处name type都行--><constructor-arg name="ds" ref="dataSource"></constructor-arg></bean><!--创建dataSource:需要四大属性参数--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring331"></property><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean></beans>

g、测试类

TestCRUD

    @Testpublic void testFindAll(){//创建容器ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");//创建service对象AccountService service= (AccountService) ac.getBean("accountService");List<Account> accountList = service.findAll();for (Account account : accountList) {System.out.println(account);}}

三、常用的注解

a、注解开发入门流程

1、引入依赖

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><!--引入单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version></dependency></dependencies>

2、配置文件::applicationContext.xml
注意添加头部(利用代码提示敲出<context:component-scan会自动帮你加上那三行头)
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--开启注解 指定扫描的包 : context:component-scan引入context名称空间-引入约束指定扫描包:base-package="" 指定包及其子包ME:开启注解扫描 然后一个注解@Component就能帮你创建对象了 强--><context:component-scan base-package="cn.ahpu"></context:component-scan>
</beans>

3、在需要创建对象的类上添加注解(eg: @Component)
UserDaoImpl

@Component
public class UserDaoImpl implements UserDao {}

UserServiceImpl

@Component
public class UserServiceImpl implements UserService {}

4、测试代码
TestAnn.java

@Testpublic void test(){//创建容器对象 尚不是存注解 还用ClassPathXmlApplicationContextApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");//获取对象UserDao userDao = ac.getBean(UserDao.class);System.out.println(userDao);UserService userService = ac.getBean(UserService.class);System.out.println(userService);}

b、常用注解

@Component

@Component -- 标记在类上,不能用在方法上
1.作用:创建对象, 只要标记了,扫描了该包,对象就会创建
2.衍生了三个子注解@Controller 一般用于web(控制层)层@Service 一般用于业务层@Repository 一般用于持久层(其实作用都一样 也可以不加区别混用  推荐三层对应使用 层次不够清楚的使用Component)
3.相当于xml<bean id="" class="全限类名"></bean>
4.属性:value="userDao"   eg:@Component("userDao")    相当于xml的 id="userDao"
5.如果没有指定value属性,默认的名称是 简单类名,首字母小写  (此处应该理解javaSE规范中的首字母大写的意义了 用框架就必须遵守规范)UserDaoImpl -- userDaoImplUserServiceImpl -- userServiceImpl

@Autowired

@Autowired -- 自动注入
可以标记在属性和set方法上,如果标记在属性上,可以没有set方法
特点:默认自动按照类型注入
流程:当属性或set方法上标记了@Autowired ,会自动在容器中查询该属性类型的对象,如果有且只有一个★,则注入(该类型多了少了都会报错)
@Qualifier :必须与@Autowired结合使用
作用:如果自动注入按照类型注入失败(该属性类型实例对象在容器中有多个),则按照指定的名称注入如果没有@Qualifier,类型注入失败,则按照属性名按照名称注入(将属性名当做实例对象的名称来匹配)建议IOC容器中有多个相同类型时一定加上@Qualifier

@Resource

@Resource -- 自动注入
流程:当属性|set方法标记了@Resource,会自动按照名称注入, 如果名称没有找到,则根据类型注入,如果类型有多个,则抛出异常

两个自动注入的区别

@Autowired : 默认按照类型注入,如果类型有多个,则按照名称注入 -- spring提供的
@Resource : 默认按照名称注入,没有名称没有找到,按照类型注入 -- jdk提供的

《纯注解开发才用到》

纯注解开发才会用到的

@Configuration

@Configuration : 标记该类为配置文件类
可以替换 applicationContext.xml

@ComponentSacn(“cn.ahpu”)

@ComponentSacn("com.itheima")
相当于:<context:component-scan base-package="com.itheima">

@Import

@Import({JDBCConfiguration.class})  引入其他配置
<import resource="classpath:applicationContext-dao.xml"></import>

@Bean

@Bean -- 通过方法创建对象,一般用于创建别人提供的类
相当于:<bean ...>

@Scope(“singleton|prototype”)

@Scope("singleton|prototype")
配置对象的范围:相当于:bean标签中的属性 scope="singleton|prototype"

eg.配置dao为单例的

生命周期

放在方法上

@PostConstruct:相当于bean标签的属性 init-method,指定初始化方法
@PreDestroy:相当于bean标签的属性:destroy-method, 指定对象的销毁方法

@Value

@Value 给属性赋值 -- 只能赋值简单类型

eg:

@PropertySource

PropertySource : 引入外部属性文件
相当于:<context:property-placeholder location="classpath:jdbc.properties"></context:propertyplaceholder>

Demo代码

UserDaoImpl.java

public class TestAnn {@Testpublic void test(){//创建容器对象 尚不是存注解 还用ClassPathXmlApplicationContextApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");//获取对象UserDao userDao = (UserDao) ac.getBean("userDao");System.out.println(userDao);//使用默认名称UserService userService = ac.getBean("userServiceImpl",UserService.class);System.out.println(userService);//测试注入userService.print();}
}

UserDaoImpl2.java

@Repository("userDao2")
public class UserDaoImpl2 implements UserDao {@Overridepublic void print() {System.out.println("持久层 userDaoImpl2");}
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {/*@Autowired //一个注解 set方法都不用给了@Qualifier("userDao") //指定具体类在容器中的名称 多保险UserDao userDao;*///优先按名称注入(未指定名称时默认名称为属性名称userDao) 名称注入失败再尝试按类型注入@Resource(name = "userDao2") //类型有多个时写上名称最保险UserDao userDao;public void print(){userDao.print();}
}

TestAnn.java

public class TestAnn {@Testpublic void test(){//创建容器对象 尚不是存注解 还用ClassPathXmlApplicationContextApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");//获取对象UserDao userDao = (UserDao) ac.getBean("userDao");System.out.println(userDao);//使用默认名称UserService userService = ac.getBean("userServiceImpl",UserService.class);System.out.println(userService);//测试注入userService.print();}
}

配置文件分解

也是纯注解中几个注解的xml方式

applicationContext.xml的分解(import 标签和context:property-placeholder)

导入xml: import
导入properties: context:property-placeholder

<!--引入外部属性文件--><context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!--引入外部配置文件--><import resource="applicationContext-dao.xml"></import>


自动导入头文件有时可能失效 所还是要整理所有头文件模板为上

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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--创建AccountService:需要AccountDao--><bean id="accountService" class="cn.ahpu.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"></property></bean><!--引入外部属性文件--><import resource="applicationContext-dao.xml"></import></beans>

applicationContext-dao.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--创建queryRunner:需要dataSource 构造方法传入的 --><bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"><!--查看QueryRunner源码然后选择合适属性 此处name type都行--><constructor-arg name="ds" ref="dataSource"></constructor-arg></bean><!--创建AccountDao:需要queryRunner--><bean id="accountDao" class="cn.ahpu.dao.impl.AccountDaoImpl"><property name="queryRunner" ref="queryRunner"></property></bean><!--创建dataSource:需要四大属性参数--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="${jdbc.url}"></property><property name="driverClass" value="${jdbc.driver}"></property><property name="user" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean><!--引入外部属性文件--><context:property-placeholder location="jdbc.properties"></context:property-placeholder></beans>

jdbc.properties

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

用得最多的两种注解:创建对象的注解和注入的注解 以后一般也不会指定注入名称 一般同一类型就一个 少数多了也会立刻报错的


补:注解扫描配置两个子标签

context:include-filter 和 context:exclude-filter

 <!--开启注解 扫描包--><context:component-scan base-package="cn.ahpu"><!--context:include-filter:指定包含过滤type="annotation":按照类型过滤expression: 过滤的表达式只扫描标记了contriller注解的类--><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter><!--context:exclude-filter:指定排除过滤type="annotation": 按照类型过滤expression: 过滤表达式不扫描controller注解(扫描除controller注解外所有注解)--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter></context:component-scan>

四、使用注解改造账户CRUD(半xml半注解方式 最常用)


快捷键输入此配置 自动导入3行头名称空间 (eclipse没有此功能 所有自己自定义一个模板最好)
IDEA的xml文件中按ctrl+alt+shift+o也可以删除多余名称空间

a、实体类

Account.java

public class Account {private Integer id;private String name;private Float money;
}

b、持久层

AccountDaoImpl

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {@Autowired //xml配置文件里已经以配置的方式创建了queryRunner类QueryRunner queryRunner;@Overridepublic List<Account> findAll() {String sql = "select * from Account";try {List<Account> accountList = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));return accountList;} catch (SQLException e) {e.printStackTrace();return null;}}
}

c、业务层

AccountServiceImpl

@Service("accountService")
public class AccountServiceImpl implements AccountService {@Autowired //基本上AccountDao类型只有一个 所以不必再指定名称或者用@Resourceprivate AccountDao accountDao;//注解不需要set方法@Overridepublic List<Account> findAll() {return accountDao.findAll();}
}

d、配置文件

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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--开启注解 扫描包--><context:component-scan base-package="cn.ahpu"></context:component-scan><!--创建queryRunner:需要dataSource 构造方法传入的 --><bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"><!--查看QueryRunner源码然后选择合适属性 此处name type都行--><constructor-arg name="ds" ref="dataSource"></constructor-arg></bean><!--创建dataSource:需要四大属性参数--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring331"></property><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean></beans>

e、测试

    @Testpublic void testFindAll(){//创建容器ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");//创建service对象AccountService service= (AccountService) ac.getBean("accountService");List<Account> accountList = service.findAll();for (Account account : accountList) {System.out.println(account);}}

五、纯注解开发

1. SpringConfiguration.java

/*** 1.标记本本类为配置文件类 @Configuration* 2.指定注解扫描的包路径 (完全没有xml了 需要有个一个专门的类管理注解) @ComponentScan({"cn.ahpu"})* 3.引入其他配置文件类  @Import({JDBCConfiguration.class})*/@Configuration
@ComponentScan({"cn.ahpu"}) //数组参数
@Import({JDBCConfiguration.class})
public class SpringConfiguration {}

2.JDBCConfiguration.java

dao和service同上

/*** 配置持久层需要的类*/
@Configuration //可有可无的配置
public class JDBCConfiguration {/*** 创建数据源对象: dataSource* @bean("name") 用在方法上 用来指定创建的对象存到容器中去*                  "name" 在容器中的名称* @return*/@Bean("dataSource") //通知容器 此处创建了类 请收纳public DataSource createDataSource() {ComboPooledDataSource dataSource = new ComboPooledDataSource();try {dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring331");dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setUser("root");dataSource.setPassword("root");} catch (PropertyVetoException e) {e.printStackTrace();}return dataSource;}@Bean("queryRunner")public QueryRunner createQueryRunner(DataSource dataSource){//容器创建queryRunner则参数肯定也会到容器中找了return new QueryRunner(dataSource);}
}

3.TestCRUD.java

    @Testpublic void testFindAll(){//纯注解创建容器对象ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);//创建service对象AccountService service= (AccountService) ac.getBean("accountService");List<Account> accountList = service.findAll();for (Account account : accountList) {System.out.println(account);}}

六、spring与junit的整合

1. 引入依赖

pom.xml

     <!--单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version></dependency><!--引入spring-5 的测试包: 必须引用相应的junit包, junit的版本必须是4.12以上--><!--引入spring-4 的测试包: 必须引用相应的junit包, junit的版本必须是4.9以上--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency>

2.1配置测试环境-- xml

a. 替换Junit的运行器: 为spring与junit整合后的运行器
@RunWith(SpringJUnit4ClassRunner.class)
b. 指定配置文件路径, 会自动创建容器对象, 必须添加classpath
@ContextConfiguration({"classpath:applicationContext.xml"})

2.2 配置测试环境-- ann 纯注解方式

a. 替换Junit的运行器: 为spring与junit整合后的运行器
@RunWith(SpringJUnit4ClassRunner.class)
b. 指定配置文件路径, 会自动创建容器对象, 必须添加classpath
@ContextConfiguration(classes = {SpringConfiguration.class})

3. 测试:从容器可以获取某类型的对象

@Autowired
AccountService accountService;

TestSpring.java XML方式

/*** 1. 替换junit运行器:为spring和junit整合后的运行器* 2. 指定配置文件的路径 : 会自动读取配置文件 也就会自动创建容器和类*  @ContextConfiguration({"classpath:applicationContext.xml"})*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class TestCRUD {@Autowired //容器已经创建了 可以自动注入了AccountService service;@Testpublic void testFindAll(){//不用每次创建容器和service了List<Account> accountList = service.findAll();for (Account account : accountList) {System.out.println(account);}}
}

TestSpring.java 纯注解方式

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class TestCRUD {@AutowiredAccountService service;@Testpublic void testFindAll(){List<Account> accountList = service.findAll();for (Account account : accountList) {System.out.println(account);}}
}

七、小结

1. spring 第二天一个账户表的CRUD -- xml常用的注解@Component -- @Controller ,@Service ,@Repository -创建对象@AutoWired :自动注入默认按照类型注入,按照名称注入结合@Qualifier:指定对象的名称@Resource :自动注入默认按照名称注入,如果没有指定名称对象,则按照类型注入@Configuration: 指定该类为配置文件类@Bean:在方法上标记,创建对象@ComponentScan:扫描包,创建对象@Import :导入其他的配置文件<import resource="">@PropertyResource: 引入属性文件--jdbc.properties   <context:property-placeholder location="" />@Value: 给属性赋值(简单类型)@Scope: 对象的范围生命周期的:了解    注解xml和ann改造账户表CRUD纯注解: 改造crudspring和junit整合@Runwith:替换junit运行器@ContextConfiguration:指定配置文件的路径

spring-day02-IOC完成CRUD、注解开发IOC相关推荐

  1. 【java学习之路】(java框架)007.IoC和DI注解开发

    IoC和DI注解开发 Spring配置数据源 数据源(连接池)的作用 • 数据源(连接池)是提高程序性能如出现的 • 事先实例化数据源,初始化部分连接资源 • 使用连接资源时从数据源中获取 • 使用完 ...

  2. 【Spring】IOC:基于注解的IOC容器初始化源码分析

    从 Spring2.0 以后的版本中,Spring 也引入了基于注解(Annotation)方式的配置,注解(Annotation)是 JDK1.5 中引入的一个新特性,用于简化 Bean 的配置,可 ...

  3. Spring不使用XML的注解开发

    这里不再用XML配置,直接用纯Java配置,首先是写一个User实体类 package com.zhiying.pojo;import org.springframework.beans.factor ...

  4. Spring(三)——HelloSpring、IOC创建对象的方式、属性注入、自动装配、使用注解开发

    文章目录 1. 简介 2. IOC理论推导 3. HelloSpring 4. IOC创建对象的方式 4.1 使用无参构造创建对象(默认) 4.2 使用有参构造创建对象 5. Spring配置 5.1 ...

  5. Spring IOC注解开发

    Spring IOC注解开发 @(Spring)[Spring, ioc, 注解] Spring IOC注解开发 Spring的IOC的注解使用步骤 创建项目引入jar包 引入配置文件 创建相关包和类 ...

  6. java day58【 案例:使用 spring 的 IoC 的实现账户的 CRUD 、 基于注解的 IOC 配置 、 Spring 整合 Junit[掌握] 】...

    第1章 案例:使用 spring 的 IoC 的实现账户的 CRUD 1.1 需求和技术要求 1.1.1 需求 1.1.2 技术要求 1.2 环境搭建 1.2.1 拷贝 jar 包 1.2.2 创建数 ...

  7. JavaSSM笔记(一)Spring基础(JavaBean)(IoC理论)(AOP)(使用注解开发)

    在JavaWeb阶段,我们已经学习了如何使用Java进行Web应用程序开发,我们现在已经具有搭建Web网站的能力,但是,我们在开发的过程中,发现存在诸多的不便,在最后的图书管理系统编程实战中,我们发现 ...

  8. 【SSM框架系列】Spring IoC(控制反转) DI(依赖注入)注解开发

    Spring注解开发 Spring是轻代码重配置的框架,配置比较繁重,会影响开发效率.这个时候可以通过注解开发,注解代替xml配置文件可以简化配置,提高开发效率. Spring原始注解 注解分为原始注 ...

  9. Spring中IOC注解开发;xml中常用字符转译

    目录 1.Spring注解主要用来替xml配置文件: 2.xml中特殊符号转译: 1.Spring注解主要用来替xml配置文件: /*spring原始注解主要代替<Bean>的配置 * * ...

最新文章

  1. 如何提高增加包含大量记录的表的主键字段的效率
  2. 树莓派python实例_树莓派3 搭建 django 服务器的实例
  3. clientdataset新增append新增多条记录的时候报错 key valation
  4. url 自动加入链接
  5. 【存储知识学习】第三章磁盘原理与技术3.6磁盘控制器、驱动器控制电路和磁盘控制器驱动程序and3.7内部传输速率和外部传输速率--《大话存储》阅读笔记
  6. miniui展示日历能点击_2020年日历设计,除了366天有新字体,还有新形式
  7. LightOJ 1278 - Sum of Consecutive Integers 分解奇因子 + 思维
  8. Loadrunner11完美破解小笔记
  9. 【人脸识别】arcface详解
  10. 日积月累系列之分页控件(js源码)
  11. java 创建消息队列_java - 在Java中动态创建异步消息队列 - 堆栈内存溢出
  12. 华硕飞行堡垒atk驱动在哪_11月8日华硕再撒大额福利 满减优惠价机不可失_第1页...
  13. java100集视频_上百集课程JAVA区块链开发视频教程
  14. linux sqlplus 历史命令,SQLPLUS下历史命令查找
  15. 魏武帝 太祖知不可匡正,遂不复献言
  16. 推荐一款国产免费开源的ERP进销存系统 附带安装详细教程
  17. fireFox post请求插件,火狐浏览器插件
  18. 苹果电池显示维修_iFixit拆解苹果iPhone 12/Pro:显示屏和电池可互换
  19. 大学生bootstrap框架网页作业成品 bootstrap响应式网页制作模板 学生海贼王动漫bootstrap框架网站作品
  20. 2000坐标系xy坐标几位_详解| 带你认识新一代坐标系——2000国家大地坐标系

热门文章

  1. Caffe中的数据填充类Filler
  2. 大数据基准测试平台BigDataBench5.0安装配置及使用
  3. 浅谈PID/PIV之精密运动控制
  4. 2022版 Tangible Software Solutions 功能齐全的源代码转换器
  5. 如何在微信给视频照片做征集投票评分,教你快速制作投票评分小程序
  6. 数据结构—邻接矩阵存储法代码实现
  7. [Java] Node和Entry
  8. 北京:2100名号贩子信息已录入医院人脸识别系统
  9. Mobile Edge Computing —— Paper List
  10. 【转】面向程序员的数据库访问性能优化法则