学習ばね2:IOCベースのアノテーションと依存性注入+ XMLを実装しました

学習ばね2:IOCベースのアノテーションと依存性注入+ 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
        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を構成するには、アノテーションを使用して第二に、

注釈付きクラスに対応するコンテナに設定するばねニーズに、次に注釈は、configure Beanに使用することができ、Beanはタグ構成を使用してコンフィギュレーションファイルを必要としません。

@Component@Controller@Service@Repository、クラスに追加これらのアノテーションは、容器に入れているオブジェクトクラスを作成するには、春を知らせました。

第三に、依存性注入の注釈に関連します

豆注入3.1

autowired

自動注入の種類に応じ。注釈注入性を使用する場合、セット方法を省略することができます。それだけで他のBeanタイプに注入することができます。豆IDとしてオブジェクト変数名を用いて注入される試合の複数の種類が存在する場合には、春のコンテナを見つけ、あなたも成功し、注射を見つけることができます。エラーで見つけることができません

Qualifier

自動注射に基づいて上記の種類に応じて、豆リフィルIDに従って。フィールド注入は、@Autowireと一緒に使用しなければならない場合には、独立して使用することはできません。しかし、パラメータの注入方法は、独立して使用することができるとき。

プロパティ:値、豆IDを指定します

Resource

ビーンのidに応じて直接注入。それだけで他のBeanタイプに注入することができます。属性:名前、豆のIDを指定

3.2単純な注入型(ベース+文字列)

Value

インジェクション基本データ型とデータ型String。属性:指定された値の値は、。

第四に、例:アカウントのCRUD操作を達成するために

アカウント上のCRUD処理を実施するように構成されたスプリングを使用して+ xmlで注釈は、持続性はコモン-dbutilsを使用して達成されます

SQLデータベースとテーブルの作成3.1

-- 创建数据库
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構成ファイル

この設定ファイル内の注釈のためのオープンサポート、豆と豆QueryRunnerの接続プールを設定します

<?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;
}

DAO、パッケージ構造と、対応するサービス実装クラスを作成する3.5

ここで、次の実装クラス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());
        }
    }

}

注射Autowiredサービスで使用されるオブジェクトのタイプを達成次いで、本方法は、DAOと呼ぶことにします

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

3.6テスト

スプリングコンテナからサービスオブジェクトを取得し、対応する方法を実行します

    @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()));
    }

V.の概要

ノートXML構成および構成プロセスが同じで、プロセス中に入れ、容器内への最初のBeanは、主な用途の依存性注入注釈が2つのノートを達成して、依存性注入の問題を含むことができるされている:@Autowiredおよび@値

例プロジェクト住所
例プロジェクトアドレス

おすすめ

転載: www.cnblogs.com/chengxuxiaoyuan/p/12154330.html