Springの@ Configuration、@ ComponentScan、@ Beanアノテーション

@構成

役割:現在のクラスが構成クラスであることを指定します。

@ComponentScan

機能:アノテーションを介してコンテナーを作成するときに、Springがスキャンするパッケージを指定するために使用されます。
プロパティ:

  • 値:basePackagesと同じ効果があります。どちらも、コンテナーの作成時にスキャンするパッケージを指定するために使用されます。このアノテーションを使用することは、xmlでの構成と同等です<context:component-scan base-package="com.qublog"></context:component-scan>
  • basePackages
@豆

役割:現在のメソッドの戻り値をBeanオブジェクトとしてSpringのIoCコンテナーに格納するために使用されます。
プロパティ:

  • name:BeanのIDを指定するために使用され、デフォルト値は現在のメソッドの名前です。

詳細:アノテーション構成メソッドを使用する場合、メソッドにパラメーターがある場合、Springフレームワークはコンテナーに移動して、Autowiredアノテーションと同じ方法で使用可能なBeanオブジェクトがあるかどうかを確認します。

例:
pom.xml

<?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>com.qublog</groupId>
    <artifactId>spring02_account_anno_ioc_withoutxml</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
</project>

アカウントクラス:

package com.qublog.domain;


import java.io.Serializable;

//账户的实体类
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

AccountDaoインターフェース:

package com.qublog.dao;

import com.qublog.domain.Account;

import java.util.List;

//账户的持久层接口
public interface AccountDao {
    //查询所有
    List<Account> findAllAccount();

    //查询一个
    Account findAccountById(Integer id);

    //保存
    void saveAccount(Account account);

    //更新
    void updateAccount(Account account);

    //删除
    void deleteAccount(Integer id);
}

AccountDaoImplクラス:

package com.qublog.dao.impl;

import com.qublog.dao.AccountDao;
import com.qublog.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(value = "accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner 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 findAccountById(Integer id) {
        try{
            return runner.query("select * from account where id=?;",new BeanHandler<Account>(Account.class),id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

    public void updateAccount(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 id) {
        try{
            runner.update("delete from account where id=?;",id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

AccountServiceインターフェース:

package com.qublog.service;

import com.qublog.domain.Account;

import java.util.List;

//账户的业务层接口
public interface AccountService {

    //查询所有
    List<Account> findAllAccount();

    //查询一个
    Account findAccountById(Integer id);

    //保存
    void saveAccount(Account account);

    //更新
    void updateAccount(Account account);

    //删除
    void deleteAccount(Integer id);
}

AccountServiceImplクラス:

package com.qublog.service.impl;

import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import com.qublog.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//账户的业务层实现类
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

SpringConfigurationクラス:

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

//该类是一个配置类,它的作用和bean.xml是一样的
//spring中的新注解:
//Configuration
//ComponentScan
@Configuration
@ComponentScan(basePackages = {"com.qublog"})
public class SpringConfiguration {

    //用于创建一个QueryRunner对象
    @Bean(name = "runner")
    @Scope(value = "prototype")
    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/springtest?serverTimezone=UTC");
            ds.setUser("root");
            ds.setPassword("1234");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

AccountServiceTestクラス:

package com.qublog.test;

import com.qublog.domain.Account;
import com.qublog.service.AccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

//使用Junit单元测试,测试我们的配置
public class AccountServiceTest {

    @Test
    public void testFindAll() {
        //获取容器
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //得到业务层对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account:accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //得到业务层对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //得到业务层对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //执行方法
        Account account = new Account();
        account.setName("test anno");
        account.setMoney(666f);
        as.saveAccount(account);
    }

    @Test
    public void testUpdate() {
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //得到业务层对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //执行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //得到业务层对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //执行方法
        as.deleteAccount(4);
    }
}
公開された56元の記事 ウォンの賞賛0 ビュー523

おすすめ

転載: blog.csdn.net/qq_41242680/article/details/105651793