1.基于注解的IOC配置

1.1导入jar包

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.itheima</groupId>
  8. <artifactId>day02_eesy_01anno_ioc</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-context</artifactId>
  16. <version>5.0.2.RELEASE</version>
  17. </dependency>
  18. </dependencies>
  19.  
  20. </project>

1.2接口

  1. package com.itheima.dao;
  2.  
  3. /**
  4. * 账户的持久层接口
  5. */
  6. public interface IAccountDao {
  7.  
  8. /**
  9. * 模拟保存账户
  10. */
  11. void saveAccount();
  12. }
  1. package com.itheima.service;
  2.  
  3. /**
  4. * 账户业务层的接口
  5. */
  6. public interface IAccountService {
  7.  
  8. /**
  9. * 模拟保存账户
  10. */
  11. void saveAccount();
  12. }

1.3创建spring的xml配置文件并开启对注解的支持

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd">
  9.  
  10. <!--把对象的创建交给spring来管理-->
  11. <!--<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>-->
  12.  
  13. <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
  14. context名称空间和约束中-->
  15. <context:component-scan base-package="com.itheima"></context:component-scan>
  16. </beans>

1.4使用@Component注解配置管理的资源

  1. package com.itheima.service.impl;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import com.itheima.service.IAccountService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.context.annotation.Scope;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.stereotype.Service;
  10.  
  11. import javax.annotation.Resource;
  12.  
  13. /**
  14. * 账户的业务层实现类
  15. *
  16. * 曾经XML的配置:
  17. * <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
  18. * scope="" init-method="" destroy-method="">
  19. * <property name="" value="" | ref=""></property>
  20. * </bean>
  21. *
  22. * 1.用于创建对象的
  23. * 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的
  24. * Component:
  25. * 作用:用于把当前类对象存入spring容器中
  26. * 属性:
  27. * value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。
  28. * Controller:一般用在表现层
  29. * Service:一般用在业务层
  30. * Repository:一般用在持久层
  31. * 以上三个注解他们的作用和属性与Component是一模一样。
  32. * 他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
  33. *
  34. * 2.用于注入数据的
  35. * 他们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的
  36. * Autowired:
  37. * 作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
  38. * 如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
  39. * 如果Ioc容器中有多个类型匹配时:首先按照类型筛选,然后按照名称筛选
  40. * 出现位置:
  41. * 可以是变量上,也可以是方法上
  42. * 细节:
  43. * 在使用注解注入时,set方法就不是必须的了。
  44. * Qualifier:
  45. * 作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以
  46. * 属性:
  47. * value:用于指定注入bean的id。
  48. * Resource
  49. * 作用:直接按照bean的id注入。它可以独立使用
  50. * 属性:
  51. * name:用于指定bean的id。
  52. * 以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
  53. * 另外,集合类型的注入只能通过XML来实现。
  54. *
  55. * Value
  56. * 作用:用于注入基本类型和String类型的数据
  57. * 属性:
  58. * value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
  59. * SpEL的写法:${表达式}
  60. *
  61. * 3.用于改变作用范围的
  62. * 他们的作用就和在bean标签中使用scope属性实现的功能是一样的
  63. * Scope
  64. * 作用:用于指定bean的作用范围
  65. * 属性:
  66. * value:指定范围的取值。常用取值:singleton prototype
  67. *
  68. * 4.和生命周期相关(了解)
  69. * 他们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的
  70. * PreDestroy
  71. * 作用:用于指定销毁方法
  72. * PostConstruct
  73. * 作用:用于指定初始化方法
  74. */
  75. @Service("accountService")
  76. @Scope("prototype")
  77. public class AccountServiceImpl implements IAccountService {
  78. // @Autowired
  79. // @Qualifier("accountDao2")
  80. @Resource(name = "accountDao1")
  81. private IAccountDao accountDao ;
  82.  
  83. public void saveAccount(){
  84. accountDao.saveAccount();
  85. }
  86. }
  1. package com.itheima.dao.impl;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import org.springframework.stereotype.Repository;
  5.  
  6. /**
  7. * 账户的持久层实现类
  8. */
  9. @Repository("accountDao1")
  10. public class AccountDaoImpl implements IAccountDao {
  11.  
  12. public void saveAccount(){
  13.  
  14. System.out.println("保存了账户1111111111");
  15. }
  16. }

1.5测试方法

  1. package com.itheima.ui;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import com.itheima.service.IAccountService;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7.  
  8. /**
  9. * 模拟一个表现层,用于调用业务层
  10. */
  11. public class Client {
  12.  
  13. public static void main(String[] args) {
  14. //1.获取核心容器对象
  15. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  16. //2.根据id获取Bean对象
  17. IAccountService as = (IAccountService)ac.getBean("accountService");
  18. IAccountService as2 = (IAccountService)ac.getBean("accountService");
  19.  
  20. System.out.println(as==as2);
  21.  
  22. // IAccountDao adao = ac.getBean("accountDao", IAccountDao.class);
  23. // System.out.println(adao);
  24. // System.out.println(as);
  25.  
  26. as.saveAccount();
  27. }
  28. }

2.常用注解

2.1用于创建对象的

  1. 相当于:<bean id="" class="">

1.@Component

2.@Controller @Service @Repository

2.2用于注入数据的

  1. 相当于:<property name="" ref="">
  2.     <property name="" value="">

1. @Autowired

 2.@Qualifier

 3.@Resource

 4.@Value

2.3用于改变作用范围的

  1. 相当于:<bean id="" class="" scope="">

1.@Scope

2.4和生命周期相关的

  1. 相当于:<bean id="" class="" init-method="" destroy-method="" />

1.@PostConstruct

2.@PreDestroy

3.使用spring的IoC的实现账户的CURD

3.1 技术要求

使用 spring 的 IoC 实现对象的管理
使用 DBAssit 作为持久层解决方案
使用 c3p0 数据源

3.2导入jar包

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.itheima</groupId>
  8. <artifactId>day02_eesy_02account_xmlioc</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-context</artifactId>
  16. <version>5.0.2.RELEASE</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-test</artifactId>
  21. <version>5.0.2.RELEASE</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>commons-dbutils</groupId>
  25. <artifactId>commons-dbutils</artifactId>
  26. <version>1.4</version>
  27. </dependency>
  28.  
  29. <dependency>
  30. <groupId>mysql</groupId>
  31. <artifactId>mysql-connector-java</artifactId>
  32. <version>5.1.6</version>
  33. </dependency>
  34.  
  35. <dependency>
  36. <groupId>c3p0</groupId>
  37. <artifactId>c3p0</artifactId>
  38. <version>0.9.1.2</version>
  39. </dependency>
  40.  
  41. <dependency>
  42. <groupId>junit</groupId>
  43. <artifactId>junit</artifactId>
  44. <version>4.12</version>
  45. </dependency>
  46. </dependencies>
  47.  
  48. </project>

3.3编写实体

  1. package com.itheima.domain;
  2.  
  3. import java.io.Serializable;
  4.  
  5. /**
  6. * 账户的实体类
  7. */
  8. public class Account implements Serializable {
  9.  
  10. private Integer id;
  11. private String name;
  12. private Float money;
  13.  
  14. public Integer getId() {
  15. return id;
  16. }
  17.  
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21.  
  22. public String getName() {
  23. return name;
  24. }
  25.  
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29.  
  30. public Float getMoney() {
  31. return money;
  32. }
  33.  
  34. public void setMoney(Float money) {
  35. this.money = money;
  36. }
  37.  
  38. @Override
  39. public String toString() {
  40. return "Account{" +
  41. "id=" + id +
  42. ", name='" + name + '\'' +
  43. ", money=" + money +
  44. '}';
  45. }
  46. }

3.4编写持久层代码

  1. package com.itheima.dao;
  2.  
  3. import com.itheima.domain.Account;
  4.  
  5. import java.util.List;
  6.  
  7. /**
  8. * 账户的持久层接口
  9. */
  10. public interface IAccountDao {
  11.  
  12. /**
  13. * 查询所有
  14. * @return
  15. */
  16. List<Account> findAllAccount();
  17.  
  18. /**
  19. * 查询一个
  20. * @return
  21. */
  22. Account findAccountById(Integer accountId);
  23.  
  24. /**
  25. * 保存
  26. * @param account
  27. */
  28. void saveAccount(Account account);
  29.  
  30. /**
  31. * 更新
  32. * @param account
  33. */
  34. void updateAccount(Account account);
  35.  
  36. /**
  37. * 删除
  38. * @param acccountId
  39. */
  40. void deleteAccount(Integer acccountId);
  41. }
  1. package com.itheima.dao.impl;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import com.itheima.domain.Account;
  5. import org.apache.commons.dbutils.QueryRunner;
  6. import org.apache.commons.dbutils.handlers.BeanHandler;
  7. import org.apache.commons.dbutils.handlers.BeanListHandler;
  8.  
  9. import java.util.List;
  10.  
  11. /**
  12. * 账户的持久层实现类
  13. */
  14. public class AccountDaoImpl implements IAccountDao {
  15.  
  16. private QueryRunner runner;
  17.  
  18. public void setRunner(QueryRunner runner) {
  19. this.runner = runner;
  20. }
  21.  
  22. @Override
  23. public List<Account> findAllAccount() {
  24. try{
  25. return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
  26. }catch (Exception e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30.  
  31. @Override
  32. public Account findAccountById(Integer accountId) {
  33. try{
  34. return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
  35. }catch (Exception e) {
  36. throw new RuntimeException(e);
  37. }
  38. }
  39.  
  40. @Override
  41. public void saveAccount(Account account) {
  42. try{
  43. runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
  44. }catch (Exception e) {
  45. throw new RuntimeException(e);
  46. }
  47. }
  48.  
  49. @Override
  50. public void updateAccount(Account account) {
  51. try{
  52. runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
  53. }catch (Exception e) {
  54. throw new RuntimeException(e);
  55. }
  56. }
  57.  
  58. @Override
  59. public void deleteAccount(Integer accountId) {
  60. try{
  61. runner.update("delete from account where id=?",accountId);
  62. }catch (Exception e) {
  63. throw new RuntimeException(e);
  64. }
  65. }
  66. }

3.5编写业务层代码

  1. package com.itheima.service;
  2.  
  3. import com.itheima.domain.Account;
  4.  
  5. import java.util.List;
  6.  
  7. /**
  8. * 账户的业务层接口
  9. */
  10. public interface IAccountService {
  11.  
  12. /**
  13. * 查询所有
  14. * @return
  15. */
  16. List<Account> findAllAccount();
  17.  
  18. /**
  19. * 查询一个
  20. * @return
  21. */
  22. Account findAccountById(Integer accountId);
  23.  
  24. /**
  25. * 保存
  26. * @param account
  27. */
  28. void saveAccount(Account account);
  29.  
  30. /**
  31. * 更新
  32. * @param account
  33. */
  34. void updateAccount(Account account);
  35.  
  36. /**
  37. * 删除
  38. * @param acccountId
  39. */
  40. void deleteAccount(Integer acccountId);
  41.  
  42. }
  1. package com.itheima.service.impl;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import com.itheima.domain.Account;
  5. import com.itheima.service.IAccountService;
  6.  
  7. import java.util.List;
  8.  
  9. /**
  10. * 账户的业务层实现类
  11. */
  12. public class AccountServiceImpl implements IAccountService{
  13.  
  14. private IAccountDao accountDao;
  15.  
  16. public void setAccountDao(IAccountDao accountDao) {
  17. this.accountDao = accountDao;
  18. }
  19.  
  20. @Override
  21. public List<Account> findAllAccount() {
  22. return accountDao.findAllAccount();
  23. }
  24.  
  25. @Override
  26. public Account findAccountById(Integer accountId) {
  27. return accountDao.findAccountById(accountId);
  28. }
  29.  
  30. @Override
  31. public void saveAccount(Account account) {
  32. accountDao.saveAccount(account);
  33. }
  34.  
  35. @Override
  36. public void updateAccount(Account account) {
  37. accountDao.updateAccount(account);
  38. }
  39.  
  40. @Override
  41. public void deleteAccount(Integer acccountId) {
  42. accountDao.deleteAccount(acccountId);
  43. }
  44. }

3.6创建并编写配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- 配置Service -->
  7. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
  8. <!-- 注入dao -->
  9. <property name="accountDao" ref="accountDao"></property>
  10. </bean>
  11.  
  12. <!--配置Dao对象-->
  13. <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
  14. <!-- 注入QueryRunner -->
  15. <property name="runner" ref="runner"></property>
  16. </bean>
  17.  
  18. <!--配置QueryRunner-->
  19. <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
  20. <!--注入数据源-->
  21. <constructor-arg name="ds" ref="dataSource"></constructor-arg>
  22. </bean>
  23.  
  24. <!-- 配置数据源 -->
  25. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  26. <!--连接数据库的必备信息-->
  27. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  28. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
  29. <property name="user" value="root"></property>
  30. <property name="password" value="123456"></property>
  31. </bean>
  32. </beans>

3.7测试

  1. package com.itheima.test;
  2.  
  3. import com.itheima.domain.Account;
  4. import com.itheima.service.IAccountService;
  5. import org.junit.Test;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;
  8.  
  9. import java.util.List;
  10.  
  11. /**
  12. * 使用Junit单元测试:测试我们的配置
  13. */
  14. public class AccountServiceTest {
  15.  
  16. @Test
  17. public void testFindAll() {
  18. //1.获取容器
  19. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  20. //2.得到业务层对象
  21. IAccountService as = ac.getBean("accountService", IAccountService.class);
  22. //3.执行方法
  23. List<Account> accounts = as.findAllAccount();
  24. for (Account account:accounts ) {
  25. System.out.println(account);
  26. }
  27.  
  28. }
  29.  
  30. @Test
  31. public void testFindOne() {
  32. //1.获取容器
  33. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  34. //2.得到业务层对象
  35. IAccountService as = ac.getBean("accountService", IAccountService.class);
  36. //3.执行方法
  37. Account account = as.findAccountById(1);
  38. System.out.println(account);
  39. }
  40.  
  41. @Test
  42. public void testSave() {
  43. Account account = new Account();
  44. account.setName("test");
  45. account.setMoney(12345f);
  46. //1.获取容器
  47. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  48. //2.得到业务层对象
  49. IAccountService as = ac.getBean("accountService", IAccountService.class);
  50. //3.执行方法
  51. as.saveAccount(account);
  52. }
  53.  
  54. @Test
  55. public void testUpdate() {
  56. //1.获取容器
  57. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  58. //2.得到业务层对象
  59. IAccountService as = ac.getBean("accountService", IAccountService.class);
  60. //3.执行方法
  61. Account account = as.findAccountById(4);
  62. account.setMoney(23456f);
  63. as.updateAccount(account);
  64. }
  65.  
  66. @Test
  67. public void testDelete() {
  68. //1.获取容器
  69. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  70. //2.得到业务层对象
  71. IAccountService as = ac.getBean("accountService", IAccountService.class);
  72. //3.执行方法
  73. as.deleteAccount(4);
  74. }
  75. }

4.使用注解完成上述案例

4.1导入jar包

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.itheima</groupId>
  8. <artifactId>day02_eesy_04account_annoioc_withoutxml</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-context</artifactId>
  16. <version>5.0.2.RELEASE</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-test</artifactId>
  21. <version>5.0.2.RELEASE</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>commons-dbutils</groupId>
  25. <artifactId>commons-dbutils</artifactId>
  26. <version>1.4</version>
  27. </dependency>
  28.  
  29. <dependency>
  30. <groupId>mysql</groupId>
  31. <artifactId>mysql-connector-java</artifactId>
  32. <version>5.1.6</version>
  33. </dependency>
  34.  
  35. <dependency>
  36. <groupId>c3p0</groupId>
  37. <artifactId>c3p0</artifactId>
  38. <version>0.9.1.2</version>
  39. </dependency>
  40.  
  41. <dependency>
  42. <groupId>junit</groupId>
  43. <artifactId>junit</artifactId>
  44. <version>4.12</version>
  45. </dependency>
  46. </dependencies>
  47.  
  48. </project>

4.2实体类

  1. package com.itheima.domain;
  2.  
  3. import java.io.Serializable;
  4.  
  5. /**
  6. * 账户的实体类
  7. */
  8. public class Account implements Serializable {
  9.  
  10. private Integer id;
  11. private String name;
  12. private Float money;
  13.  
  14. public Integer getId() {
  15. return id;
  16. }
  17.  
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21.  
  22. public String getName() {
  23. return name;
  24. }
  25.  
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29.  
  30. public Float getMoney() {
  31. return money;
  32. }
  33.  
  34. public void setMoney(Float money) {
  35. this.money = money;
  36. }
  37.  
  38. @Override
  39. public String toString() {
  40. return "Account{" +
  41. "id=" + id +
  42. ", name='" + name + '\'' +
  43. ", money=" + money +
  44. '}';
  45. }
  46. }

4.3持久层代码

  1. package com.itheima.dao;
  2.  
  3. import com.itheima.domain.Account;
  4.  
  5. import java.util.List;
  6.  
  7. /**
  8. * 账户的持久层接口
  9. */
  10. public interface IAccountDao {
  11.  
  12. /**
  13. * 查询所有
  14. * @return
  15. */
  16. List<Account> findAllAccount();
  17.  
  18. /**
  19. * 查询一个
  20. * @return
  21. */
  22. Account findAccountById(Integer accountId);
  23.  
  24. /**
  25. * 保存
  26. * @param account
  27. */
  28. void saveAccount(Account account);
  29.  
  30. /**
  31. * 更新
  32. * @param account
  33. */
  34. void updateAccount(Account account);
  35.  
  36. /**
  37. * 删除
  38. * @param acccountId
  39. */
  40. void deleteAccount(Integer acccountId);
  41. }
  1. package com.itheima.dao.impl;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import com.itheima.domain.Account;
  5. import org.apache.commons.dbutils.QueryRunner;
  6. import org.apache.commons.dbutils.handlers.BeanHandler;
  7. import org.apache.commons.dbutils.handlers.BeanListHandler;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Repository;
  10.  
  11. import java.util.List;
  12.  
  13. /**
  14. * 账户的持久层实现类
  15. */
  16. @Repository("accountDao")
  17. public class AccountDaoImpl implements IAccountDao {
  18.  
  19. @Autowired
  20. private QueryRunner runner;
  21.  
  22. @Override
  23. public List<Account> findAllAccount() {
  24. try{
  25. return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
  26. }catch (Exception e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30.  
  31. @Override
  32. public Account findAccountById(Integer accountId) {
  33. try{
  34. return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
  35. }catch (Exception e) {
  36. throw new RuntimeException(e);
  37. }
  38. }
  39.  
  40. @Override
  41. public void saveAccount(Account account) {
  42. try{
  43. runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
  44. }catch (Exception e) {
  45. throw new RuntimeException(e);
  46. }
  47. }
  48.  
  49. @Override
  50. public void updateAccount(Account account) {
  51. try{
  52. runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
  53. }catch (Exception e) {
  54. throw new RuntimeException(e);
  55. }
  56. }
  57.  
  58. @Override
  59. public void deleteAccount(Integer accountId) {
  60. try{
  61. runner.update("delete from account where id=?",accountId);
  62. }catch (Exception e) {
  63. throw new RuntimeException(e);
  64. }
  65. }
  66. }

4.4业务层代码

  1. package com.itheima.service;
  2.  
  3. import com.itheima.domain.Account;
  4.  
  5. import java.util.List;
  6.  
  7. /**
  8. * 账户的业务层接口
  9. */
  10. public interface IAccountService {
  11.  
  12. /**
  13. * 查询所有
  14. * @return
  15. */
  16. List<Account> findAllAccount();
  17.  
  18. /**
  19. * 查询一个
  20. * @return
  21. */
  22. Account findAccountById(Integer accountId);
  23.  
  24. /**
  25. * 保存
  26. * @param account
  27. */
  28. void saveAccount(Account account);
  29.  
  30. /**
  31. * 更新
  32. * @param account
  33. */
  34. void updateAccount(Account account);
  35.  
  36. /**
  37. * 删除
  38. * @param acccountId
  39. */
  40. void deleteAccount(Integer acccountId);
  41.  
  42. }
  1. package com.itheima.service.impl;
  2.  
  3. import com.itheima.dao.IAccountDao;
  4. import com.itheima.domain.Account;
  5. import com.itheima.service.IAccountService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8.  
  9. import java.util.List;
  10.  
  11. /**
  12. * 账户的业务层实现类
  13. */
  14. @Service("accountService")
  15. public class AccountServiceImpl implements IAccountService{
  16.  
  17. @Autowired
  18. private IAccountDao accountDao;
  19.  
  20. @Override
  21. public List<Account> findAllAccount() {
  22. return accountDao.findAllAccount();
  23. }
  24.  
  25. @Override
  26. public Account findAccountById(Integer accountId) {
  27. return accountDao.findAccountById(accountId);
  28. }
  29.  
  30. @Override
  31. public void saveAccount(Account account) {
  32. accountDao.saveAccount(account);
  33. }
  34.  
  35. @Override
  36. public void updateAccount(Account account) {
  37. accountDao.updateAccount(account);
  38. }
  39.  
  40. @Override
  41. public void deleteAccount(Integer acccountId) {
  42. accountDao.deleteAccount(acccountId);
  43. }
  44. }

4.5主配置类

  1. package config;
  2.  
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Import;
  5. import org.springframework.context.annotation.PropertySource;
  6.  
  7. /**
  8. * 该类是一个配置类,它的作用和bean.xml是一样的
  9. */
  10.  
  11. @ComponentScan(basePackages = {"com.itheima"})
  12. @Import(JdbcConfig.class)
  13. @PropertySource("classpath:jdbcConfig.properties")
  14. public class SpringConfiguraiton {
  15.  
  16. }

4.6数据库连接配置类

  1. package config;
  2.  
  3. import com.mchange.v2.c3p0.ComboPooledDataSource;
  4. import org.apache.commons.dbutils.QueryRunner;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.Scope;
  9.  
  10. import javax.sql.DataSource;
  11.  
  12. public class JdbcConfig {
  13. @Value("${jdbc.driver}")
  14. private String driver;
  15.  
  16. @Value("${jdbc.url}")
  17. private String url;
  18.  
  19. @Value("${jdbc.username}")
  20. private String username;
  21.  
  22. @Value("${jdbc.password}")
  23. private String password;
  24.  
  25. @Bean(name = "runner")
  26. @Scope("prototype")
  27. public QueryRunner createQueryRunner(DataSource dataSource) {
  28. return new QueryRunner(dataSource);
  29. }
  30.  
  31. @Bean(name = "dataSource")
  32. public DataSource createDataSource() {
  33. try {
  34. ComboPooledDataSource ds = new ComboPooledDataSource();
  35. ds.setDriverClass(driver);
  36. ds.setJdbcUrl(url);
  37. ds.setUser(username);
  38. ds.setPassword(password);
  39. return ds;
  40. } catch (Exception e) {
  41. throw new RuntimeException(e);
  42. }
  43. }
  44. }

4.7数据库配置文件

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/eesy
  3. jdbc.username=root
  4. jdbc.password=123456

4.8测试类

  1. package com.itheima.test;
  2.  
  3. import config.SpringConfiguraiton;
  4. import com.itheima.domain.Account;
  5. import com.itheima.service.IAccountService;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;
  11.  
  12. import java.util.List;
  13.  
  14. /**
  15. * 使用Junit单元测试:测试我们的配置
  16. */
  17. public class AccountServiceTest {
  18.  
  19. private ApplicationContext ac;
  20. private IAccountService as;
  21.  
  22. @Before
  23. public void init() {
  24. //1.获取容易
  25. ac = new AnnotationConfigApplicationContext(SpringConfiguraiton.class);
  26. //2.得到业务层对象
  27. as = ac.getBean("accountService", IAccountService.class);
  28. }
  29.  
  30. @Test
  31. public void testFindAll() {
  32.  
  33. //3.执行方法
  34. List<Account> accounts = as.findAllAccount();
  35. for (Account account : accounts) {
  36. System.out.println(account);
  37. }
  38. }
  39.  
  40. @Test
  41. public void testFindOne() {
  42. //1.获取容易
  43. // ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  44. ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguraiton.class);
  45. //2.得到业务层对象
  46. IAccountService as = ac.getBean("accountService", IAccountService.class);
  47. //3.执行方法
  48. Account account = as.findAccountById(1);
  49. System.out.println(account);
  50. }
  51.  
  52. @Test
  53. public void testSave() {
  54. Account account = new Account();
  55. account.setName("test");
  56. account.setMoney(12345f);
  57. //1.获取容易
  58. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  59. //2.得到业务层对象
  60. IAccountService as = ac.getBean("accountService", IAccountService.class);
  61. //3.执行方法
  62. as.saveAccount(account);
  63.  
  64. }
  65.  
  66. @Test
  67. public void testUpdate() {
  68. //1.获取容易
  69. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  70. //2.得到业务层对象
  71. IAccountService as = ac.getBean("accountService", IAccountService.class);
  72. //3.执行方法
  73. Account account = as.findAccountById(4);
  74. account.setMoney(23456f);
  75. as.updateAccount(account);
  76. }
  77.  
  78. @Test
  79. public void testDelete() {
  80. //1.获取容易
  81. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  82. //2.得到业务层对象
  83. IAccountService as = ac.getBean("accountService", IAccountService.class);
  84. //3.执行方法
  85. as.deleteAccount(4);
  86. }
  87. }

5.新注解说明

5.1@Configuration

5.2@ComponentScan

5.3@Bean

5.4@PropertySource

5.5@Import

6.spring整合junit案例

6.1问题

6.2解决思路分析

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

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

6.4使用@ContextConfiguration  指定spring 配置文件/对象的位置

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

6.6测试类

  1. package com.itheima.test;
  2.  
  3. import config.SpringConfiguration;
  4. import com.itheima.domain.Account;
  5. import com.itheima.service.IAccountService;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;
  12. import org.springframework.test.context.ContextConfiguration;
  13. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  14.  
  15. import java.util.List;
  16.  
  17. /**
  18. * 使用Junit单元测试:测试我们的配置
  19. * Spring整合junit的配置
  20. * 1、导入spring整合junit的jar(坐标)
  21. * 2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
  22. * @Runwith
  23. * 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
  24. * @ContextConfiguration
  25. * locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
  26. * classes:指定注解类所在地位置
  27. *
  28. * 当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
  29. */
  30. @RunWith(SpringJUnit4ClassRunner.class)
  31. @ContextConfiguration(classes = SpringConfiguration.class)
  32. public class AccountServiceTest {
  33.  
  34. @Autowired
  35. private IAccountService as;
  36.  
  37. @Test
  38. public void testFindAll() {
  39.  
  40. //3.执行方法
  41. List<Account> accounts = as.findAllAccount();
  42. for (Account account : accounts) {
  43. System.out.println(account);
  44. }
  45. }
  46.  
  47. }

23_2spring的常用注解的更多相关文章

  1. Spring系列之Spring常用注解总结

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...

  2. SpringMVC常用注解實例詳解3:@ResponseBody

    我的開發環境框架:        springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...

  3. SpringMVC常用注解實例詳解2:@ModelAttribute

    我的開發環境框架:        springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...

  4. Spring常用注解汇总

    本文汇总了Spring的常用注解,以方便大家查询和使用,具体如下: 使用注解之前要开启自动扫描功能 其中base-package为需要扫描的包(含子包). <context:component- ...

  5. Spring常用注解,自动扫描装配Bean

    1 引入context命名空间(在Spring的配置文件中),配置文件如下: xmlns:context="http://www.springframework.org/schema/con ...

  6. springmvc常用注解与类型转换

    springmvc常用注解与类型转换 一:前置 spring -servlet.xml 注入 <!-- 启用spring mvc 注解 --> <context:annotation ...

  7. SpringMVC常用注解,返回方式,路径匹配形式,验证

    常用注解元素 @Controller 标注在Bean的类定义处 @RequestMapping 真正让Bean具备 Spring MVC Controller 功能的是 @RequestMapping ...

  8. SpringMVC 常用注解

    本文参考了博客,具体请见:http://www.cnblogs.com/leskang/p/5445698.html Spring MVC的常用注解 1.@Controller @Controller ...

  9. spring注解开发中常用注解以及简单配置

    一.spring注解开发中常用注解以及简单配置 1.为什么要用注解开发:spring的核心是Ioc容器和Aop,对于传统的Ioc编程来说我们需要在spring的配置文件中邪大量的bean来向sprin ...

随机推荐

  1. 20190521 - macOS 中显示隐藏文件的快捷键

    macOS 中显示隐藏文件,以前总是借助于命令行或第三方软件,其实有一个快捷键: shift + cmmand + .

  2. VMware Workstation 12许可证

    VMware 12专业版永久许可证密钥: 5A02H-AU243-TZJ49-GTC7K-3C61N VF5XA-FNDDJ-085GZ-4NXZ9-N20E6 UC5MR-8NE16-H81WY-R ...

  3. 【Abode Air程序开发】打包并导出

    打包并导出 将移动设备应用程序打包并导出到在线商店 导出用于发行的 Android APK 包 导出用于发行的 Apple iOS 包 使用命令行进行创建.测试和部署 使用 mxmlc 编译手机应用程 ...

  4. Web工作方式

    我们平时浏览网页的时候,会打开浏览器,输入网址后按下回车键,然后就会显示出你想要浏览的内容.在这个看似简单的用户行为背后,到底隐藏了些什么呢? 对于普通的上网过程,系统其实是这样做的:浏览器本身是一个 ...

  5. 生成器的send方法、递推函数、匿名函数及常用内置函数

    生成器的send方法 在使用yield方法创建生成器时,不仅可以使用next方法进行取值,还可以通过send方法向生成器的内部传值 什么是send方法? send方法相当于高级的next方法,send ...

  6. hadoop集群搭建及易踩坑收录

    配置前先把域名映射配好哈 详情参考我的其他随笔(哪里不通可以在下方评论) 下载好hdfs.tar.gz 后 在/home/ldy下 mkdir apps/ tar -xzvf hdfs.tar.gz  ...

  7. 对Android应用签名

    Android使用包名作为唯一标识,当在同一台手机安装两个包名相同的应用,后安装的应用就会覆盖前面的应用(签名相同的情况下). 签名有两个主要作用: 1.确定发布者身份.由于应用开发者可以通过使用相同 ...

  8. Firebase Chat (firebase 实现web聊天室)

    基于firebase + cloud Function 实现web聊天(demo版) 知识点: 使用Firebase SDK创建Google Cloud功能. 触发云功能基于Auth,云存储和Clou ...

  9. Java多线程(一):线程与进程

    1.线程和进程 1.1 进程 进程是操作系统的概念,我们运行的一个TIM.exe就是一个进程. 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位 ...

  10. Where is __dso_handle defined?

    Where is __dso_handle defined? 来源  https://stackoverflow.com/questions/34308720/where-is-dso-handle- ...