Spring框架CRUD(配置文件+注解)

Spring框架CRUD(配置文件+注解)


注解开发流程


  1. 导入依赖
  2. 配置文件 applicationContext.xml
  3. 在需要创建对象的类上添加注解
  4. 测试

具体实现



  1. 导入依赖
    <?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>cn.kgc</groupId>
      <artifactId>springCRUD03Annotation</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <name>springCRUD03Annotation</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.36</version>
          </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
        </dependency>
        <dependency>
          <groupId>commons-dbutils</groupId>
          <artifactId>commons-dbutils</artifactId>
          <version>1.6</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>5.0.2.RELEASE</version>
        </dependency>
      </dependencies>
    1. 注意:Spring内置测试包是在junit4包基础上再次扩展,导入的测试依赖包需要junit 4.12 or higher
  2. 配置文件 applicationContext.xml
    1. 需要在配置文件中引入约束
      <context:component-scan base-package=""/>
      目的:<!--开启注解 扫描包--> base-package设置能设置注解的包范围
      <?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 http://www.springframework.org/schema/context/spring-context.xsd">
          <context:component-scan base-package="cn.kgc"/>
          <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
              <constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
          </bean>
          <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.user}"/>
              <property name="password" value="${jdbc.password}"/>
          </bean>
          <context:property-placeholder location="jdbc.properties"/>
      </beans>

       

  3. 在需要创建对象的类上添加注解
    1. @Service("accountService")
      public class AccountServiceImpl implements AccountService {
          @Autowired
          private AccountDao accountDao;
      相当于:
      <bean id="accountService" class="cn.kgc.service.impl.AccountServiceImpl">
          <property name="accountDao" ref="accountDao"/>
      </bean>@Repository("accountDao")
    2. @Repository("accountDao")
      public class AccountDaoImpl implements AccountDao {
          @Autowired
          QueryRunner queryRunner;
      相当于:
      <bean id="accountDao" class="cn.kgc.dao.impl.AccountDaoImpl">
          <property name="queryRunner" ref="queryRunner"/>
      </bean>
      <?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 http://www.springframework.org/schema/context/spring-context.xsd">
          
          <context:component-scan base-package="cn.kgc"/>
          <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
              <constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
          </bean>
          <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.user}"/>
              <property name="password" value="${jdbc.password}"/>
          </bean>
          <context:property-placeholder location="jdbc.properties"/>
      </beans>

       

  4. 测试
    1. @RunWith(SpringJUnit4ClassRunner.class)//用spring的测试类代替Junit4测试类
      @ContextConfiguration({"classpath:applicationContext-dao.xml"})//测试类启动时需要载入的配置文件,然后根据配置文件建立IOC容器
      相当于:
      ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

 

@Autowired  //自动实例化对象(从IOC容器中查找需要的对象)
AccountService accountService;
相当于:
AccountServiceImpl accountService = ac.getBean("accountService", AccountServiceImpl.class);
  • 添加注解前代码

    package cn.kgc;
    
            import cn.kgc.pojo.Account;
            import cn.kgc.service.impl.AccountServiceImpl;
            import org.junit.Rule;
            import org.junit.Test;
            import org.springframework.context.support.ClassPathXmlApplicationContext;
    
            import java.util.List;
    
    public class TestSpringCRUD {
        @Test
        public void testFindAll(){
            ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountServiceImpl accountService = ac.getBean("accountService", AccountServiceImpl.class);
            List<Account> accountList = accountService.findAll();
            for (Account acc : accountList) {
                System.out.println(acc);
            }
        }
        @Test
        public void testFindById(){
            ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountServiceImpl accountService = ac.getBean("accountService", AccountServiceImpl.class);
            Account account = accountService.findById(2);
            System.out.println(account);
        }
        @Test
        public void testInsert(){
            ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountServiceImpl accountService = ac.getBean("accountService", AccountServiceImpl.class);
            Account account = new Account();
            account.setName("关羽");
            account.setMoney(235467f);
            accountService.insert(account);
            testFindAll();
        }
        @Test
        public void testUpdate(){
            ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountServiceImpl accountService = classPathXmlApplicationContext.getBean("accountService", AccountServiceImpl.class);
            Account account = new Account();
            account.setId(13);
            account.setMoney(1f);
            account.setName("狗蛋");
            accountService.update(account);
            testFindAll();
        }
        @Test
        public void testDelete(){
            ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountServiceImpl accountService = ac.getBean("accountService", AccountServiceImpl.class);
            accountService.delete(13);
            testFindAll();
        }
    
    }
    

     

  • 添加注解后代码

    package cn.kgc;
    
            import cn.kgc.pojo.Account;
            import cn.kgc.service.AccountService;
            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)//用spring的测试类代替Junit4测试类
    @ContextConfiguration({"classpath:applicationContext-dao.xml"})//测试类启动时需要载入的配置文件,然后根据配置文件建立IOC容器
    public class TestSpringCRUD {
        @Autowired  //自动实例化对象(从IOC容器中查找需要的对象)
        AccountService accountService;
        @Test
        public void testFindAll(){
    
            List<Account> accountList = accountService.findAll();
            for (Account acc : accountList) {
                System.out.println(acc);
            }
        }
        @Test
        public void testFindById(){
    
            Account account = accountService.findById(2);
            System.out.println(account);
        }
        @Test
        public void testInsert(){
    
            Account account = new Account();
            account.setName("关羽");
            account.setMoney(235467f);
            accountService.insert(account);
            testFindAll();
        }
        @Test
        public void testUpdate(){
            Account account = new Account();
            account.setId(13);
            account.setMoney(1f);
            account.setName("狗蛋");
            accountService.update(account);
            testFindAll();
        }
        @Test
        public void testDelete(){
            accountService.delete(13);
            testFindAll();
        }
    
    }
    

     

总结

  1. @Componet     需要创建对象的类上加上注解  只能用在类上  不能用在方法上 衍生了三个注解
    1. @Controller  一般用于web 层
    2. @Service    一般用于Service层
    3. @Repository()   一般用于持久层
      相当于配置文件 <bean id="" class="权限类名"></bean>
  2. @Autowired  自动注入

    可以标记在属性   set方法上   但是如果没有set方法      直接标记属性上就可以

    ​        默认自动按照类型注入

    ​                流程 :属性|set方法标记了@Autowired 会自动在容器中查找该属性类型的对象 如果只有一个 注入

    ​               @Qualitfer  必须和Autowired结合使用   

  3. @Resource  自动注入

  4. @Autowired   默认按类型注入   如果类型有多个  按类型的名字     spring 提供的

    ​       @Resource    默认 按照名称 如果没有名字  按照类型      jdk 提供的
     

  5. @ Configuration:  标记该类为配置文件

  6. @ComponentSacn("cn.kgc");

    ​        <context:component-scan base-package="cn.kgc"></context:component-scan>
     

  7. @import  引入其他配置文件

  8. @Bean  通过方法创建对象  一般用于创建别人提供的类

    ​        相当于<bean id >

  9. @Scop("singleton|prototype")   相当于bean  中属性 scope

  10. @PostConstruct   相当于初始化 int-method  

    ​          @PreDstory
     

  11. @Value      给属性赋值

  12. PropertySource  引入外部文件

    ​                <context:property.....

spring和junit的整合


1  引入依赖

<!--spring-5的测试包  必须引入相应的junit包   junit版本必须是4.12以上版本-->

2   配置测试环境

替换junit的运行器 : 为spring和junit整合后的运行器

@RunWith(SpringJUnit4ClassRunner.class)

3  测试 从容器获得某类型的对象

@Autowired
    AccountService accountService;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值