zoukankan      html  css  js  c++  java
  • spring学习2:基于注解+xml实现ioc和依赖注入

    spring学习2:基于注解+xml实现ioc和依赖注入

    一、在spring配置文件中开启spring对注解的支持

    <?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">
    
        <!--基于注解+xml的spring配置-->
        <!-- 告知spring在创建容器时要扫描的包 -->
        <context:component-scan base-package="com.lyy"></context:component-scan>
    
    </beans>
    

    二、使用注解来配置要创建的bean

    在需要放到spring容器中的类上加上对应注解,这时可以使用注解来配置bean,不需要在配置文件中用bean标签来配置。

    @Component,@Controller,@Service,@Repository,这几个注解加在类上,告知spring把所在的类创建对象放入容器中。

    三、依赖注入相关的注解

    3.1 注入一个bean

    autowired

    自动按照类型注入。当使用注解注入属性时, set 方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到就报错

    Qualifier

    在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和 @Autowire 一起使用;但是给方法参数注入时,可以独立使用。

    属性:value,指定bean的id

    Resource

    直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。 属性:name,指定bean的id

    3.2注入简单类型(基本+String)

    Value

    注入基本数据类型和 String 类型数据的 。属性:value,用于指定值。

    四、实例:实现一个对账户的crud操作

    使用spring的注解+xml配置来实现一个对账户的crud操作,持久层使用commons-dbutils来实现

    3.1 创建数据库和表的sql

    -- 创建数据库
    CREATE DATABASE spring_demo1;
    SHOW TABLES;
    USE spring_demo1;
    -- 创建账户表
    CREATE TABLE account(
      id VARCHAR(64) PRIMARY KEY,
      `name` VARCHAR(32),
      money FLOAT
    )
    
    -- 新增记录
    INSERT INTO account(id,`name`,money) VALUE(MD5(UUID()),'张三',100);
    
    SELECT * FROM account 
    

    3.2 maven依赖

    <dependencies>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.16</version>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    
            <!--spring-->
            <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>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>5.0.2.RELEASE</version>
            </dependency>
    
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.46</version>
            </dependency>
    
            <!--数据库连接池-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.11</version>
            </dependency>
    
            <!--JDBC工具类库-->
            <dependency>
                <groupId>commons-dbutils</groupId>
                <artifactId>commons-dbutils</artifactId>
                <version>1.6</version>
            </dependency>
        </dependencies>
    

    3.3 spring的配置文件

    在这个配置文件中开启对注解的支持,配置连接池的bean和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"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           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
    	http://www.springframework.org/schema/aop
    	http://www.springframework.org/schema/aop/spring-aop.xsd
    	http://www.springframework.org/schema/tx
    	http://www.springframework.org/schema/tx/spring-tx.xsd">
    
        <!-- 开启注解扫描,管理service和dao -->
        <context:component-scan base-package="com.lyy.service">
        </context:component-scan>
        <context:component-scan base-package="com.lyy.dao">
    
        </context:component-scan>
    
        <context:property-placeholder location="classpath:db.properties"/>
        <!-- 配置连接池 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
    
        <!--配置common-dbutils的核心对象-->
        <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
            <constructor-arg name="ds" ref="dataSource"/>
        </bean>
    </beans>
    

    3.4创建实体类

    import lombok.Data;
    
    /**
     * 账户实体类
     */
    @Data
    public class Account {
        private String id;
        private String name;
        private float money;
    }
    

    3.5创建dao、service的包结构和对应的实现类

    其中dao实现类如下

    
    @Repository(value = "accountDaoImpl2")
    public class AccountDaoImpl2 implements IAccountDao {
    
        @Autowired
        private DataSource dataSource;
    
        @Autowired
        private QueryRunner queryRunner;
    
        @Override
        public void insert(Account account) {
            try {
                String sql="INSERT INTO account(id,`name`,money) VALUE(MD5(UUID()),?,?)";
                Object[] params={account.getName(),account.getMoney()};
                queryRunner.update(sql,params);
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("新增记录出错,e"+e.toString());
            }
        }
    
        @Override
        public List<Account> findAll() {
            try {
                String sql="SELECT * FROM account";
                List list = (List) queryRunner.query(sql, new BeanListHandler(Account.class));
                return list;
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("查询全部记录出错,e"+e.toString());
            }
        }
    
        @Override
        public Account findById(String id) {
            try {
                String sql="SELECT * FROM account WHERE id=?";
                Account account = queryRunner.query(sql, new BeanHandler<>(Account.class), id);
                return account;
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("查询指定记录出错,e"+e.toString());
            }
        }
    
        @Override
        public void delete(String id) {
            try {
                String sql="DELETE FROM account WHERE id=?";
                queryRunner.update(sql,id);
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("删除指定记录出错,e"+e.toString());
            }
        }
    
    }
    

    然后在service实现类中用Autowired注入这个对象,就可以调用dao的方法

    	@Autowired
        @Qualifier(value = "accountDaoImpl2")
        private IAccountDao accountDao;
    

    3.6测试

    从spring容器中获取service对象,并执行对应的方法

    	@Test
        public void testFindAll(){
            ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
            IAccountService accountService = app.getBean(IAccountService.class);
            List<Account> list = accountService.findAll();
            System.out.println(Arrays.toString(list.toArray()));
        }
    

    五、总结

    注解配置和xml配置的过程是一样的,都是先把bean放入容器,放入的过程中可能会涉及到依赖注入的问题,用注解实现依赖注入主要用到两个注解:@Autowired和@Value

    示例工程地址
    示例工程地址

  • 相关阅读:
    【Unity编程】欧拉角与万向节死锁(图文版)
    关于ListView中getView被重复调用的问题
    svn 错误集锦续
    android 无法生成R文件的原因剖析
    SVN下错误集锦
    视频文件格式
    国内各视频网站android pad客户端支持分辨率情况初步统计
    android 下的网络图片加载
    遇到问题描述:Android Please ensure that adb is correctly located at问题解决
    android 时间控件概述
  • 原文地址:https://www.cnblogs.com/chengxuxiaoyuan/p/12154330.html
Copyright © 2011-2022 走看看