Spring注解

Spring注解

告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为context名称空间和约束中
创建对象的注解

@Component
作用:用于把当前类对象存入spring容器中
属性:
value:用于指定bean的id。当我们不写时,它默认值是当前类名,且首字母改小写。
@Controller:一般用于表现层
@Service:一般用于业务层
@Repository:一般用于成就层
以上三个注解他们作用和属性与Component是一模一样.
他们是哪个是spring是为我们提供三层使用的注解。使我们三层的对象更加清晰

<context:componet-scan base-packge="指定扫描包"></context:component-scan>

@ComponentScan: 指定包路径扫描,把@Controller、@Service、@Repository,@Component标注的类,实例化到spring容器中

用于注入数据的
他们的作用就和xml配置文件的bean标签中写一个< property>标签作用是一样的
   Autowired:
     作用:自动按照类型注入。只要容器中有唯一的ben对象类型和要注入的变量类型匹配。就可以注入成功
   Qualifier:
     作用:按照类中注入的基础之上再按照名称注入。它在给类成员注入不能单独使用
     必须和Autowired一起使用,可以指定想注入的类
     属性:
   value:用于指定注入bean的id
出现位置:
   可以是成员变量上,也可以是方法上
细节:
   使用注解注入时,set方法就不是必须的
   Resource
   作用:直接按照bean的id注入。它可以单独使用
   属性:
   name:用于指定bean的id
以上是哪个注入都只能注入其他bean类型数据,而基本类型和String类型无法使用上述注解实现。
   另外,集合类型的注入只能通过XML来实现
   Value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
   SpEL的写法:${表达式}

生命周期相关 了解
他们的作用和在bean标签中使用inti-method和destory-method的作用是一样的
perDestroy
作用:用于指定销毁方法 (多列对象spring不负责)
PostConstrruct
作用:用于指定初始化方法

DbUtils

ArrayHandler:把结果集中的第一行数据转成对象数组。
ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。
BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。//重点
MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。//重点
MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
ColumnListHandler:将结果集中某一列的数据存放到List中。
KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里(List),再把这些map再存到一个map里,其key为指定的列。

实现的代码

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 {

    @Autowired
    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e){

            throw new RuntimeException(e);
        }

    }



    public Account findAcountByid(Integer accountId) {
        try{
            String sql =" select * from account where id = ?";
            Account s = runner.query( sql, new BeanHandler<Account>(Account.class),accountId);
            return s;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void savaAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)",account.getName(), account.getMoney());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void updataAccount(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);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id = ?",accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }


}

去除bean,xml注解 (可以去除注解的方式的操作)
原来的bean.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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--告知Spring在创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源 -->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

</beans>

通过创建的一个类,通过注解来实现bean.xml的操作

该类是一个配置类,它的作用和bean.xml是一样的
该类是一个配置类,它的作用和bean.xml是一样的

;Spring中的新注解
configuration

作用:指定当前类是一个配置类
ComponentScan

    用于:通过注解指定Spring在创建容器时候要扫描的包
    我们使用了此注解就等同于在xml配置了
    <context:componet-scan base-packge="指定扫描包"></context:component-scan>
 Bean
    作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
    属性:
    
        name用于指定bean的id.当不写时,默认值就是当前方法的名称
    细节:
        当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
        查找的方式和Autowired注解的作用是一样的
     Import:
        作用:用于导入其他配置类
        属性:
            value:用于指定其他配置类的字节码
                当我们使用Import的注解之后,有Import的类的类就是父配置类
                导入的都是子配置类
         propertySource
         	作用:用于指定properties文件位置
         	属性:
         		value:指定文件的名称和路径
         		关键字:classpath表示当前路径       
@Configuration
@ComponentScan(value={"com.itheima"})
public class SpringConfigueration {

    @Bean(name = "runner")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }
    /*
        创建数据源对象
     */
    @Bean(name = "dataSource")
    public DataSource createdataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.cj.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy");
            ds.setUser("root");
            ds.setPassword("123456");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}

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

1.为什么要整合
因为程序的冗余代码ApplicationContext
2.整合的思路
使用junit提供的一个注解把原有的main方法替换了,替换一个为Spring提供的@Runwith
告知SPring的运行器,Spring和ioc创建是基于xml还是注解的
  并说明位置@ContextConfiguration,classes:指定注解所在的位置

整合的代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfigueration.class)
public class AccountServiceTest {
    @Autowired
    private  IAccountService as =null;
    @Test
    public  void testFindAll(){
       List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值