@Configuration, @ComponentScan and @Bean annotations in Spring

@Configuration

Role: Specifies that the current class is a configuration class.

@ComponentScan

Function: Used to specify the package to be scanned by spring when creating a container through annotations.
Attributes:

  • value: It has the same effect as basePackages, both are used to specify the packages to be scanned when creating the container. We use this annotation is equivalent to configuring in xml<context:component-scan base-package="com.qublog"></context:component-scan>
  • basePackages
@Bean

Role: Used to store the return value of the current method as a bean object in spring's IoC container.
Attributes:

  • name: used to specify the id of the bean, the default value is the name of the current method.

Details: When we use the annotation configuration method, if the method has parameters, the spring framework will go to the container to find if there are available bean objects in the same way as the Autowired annotation.

Example:
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>

Account class:

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 interface:

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 class:

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 interface:

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 class:

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 class:

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 class:

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);
    }
}
Published 56 original articles · liked 0 · visits 523

Guess you like

Origin blog.csdn.net/qq_41242680/article/details/105651793