Spring Basics-Annotation-based entry case

1. Create a Maven project

IDEA2020 remember to select quickstart
to import related configuration
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>org.example</groupId>
  <artifactId>day02_XmlIocCase</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>day02_XmlIocCase</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.7</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.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!--添加配置跳过测试-->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
          <configuration>
            <skipTests>true</skipTests>
          </configuration>
        </plugin>
        <!--添加配置跳过测试-->
      </plugins>
    </pluginManagement>
  </build>
</project>

2. Create an entity class

Create a domain package and create Account.java at the same time


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 +
                '}';
    }
}

3. Create business layer interface and implementation class

Business layer interface: IAccountService.java

import org.example.domain.Account;

import java.util.List;

/*
* 业务层接口
* */
public interface AccountService {
    
    
    // 查询所有
    List<Account> findAll();

    // 根据id查询
    Account findById(Integer accountId);

    // 插入数据
    void insert(Account account);

    // 更新数据
    void update(Account account);

    // 根据Id删除数据
    void delete(Integer accountId);
}

Business layer implementation class: AccountServiceImpl.java

import org.example.dao.IAccountDao;
import org.example.domain.Account;
import org.example.service.AccountService;

import java.util.List;

/*
* 业务层接口的实现类
* */
@Service("accountService")
public class IAccountServiceImpl implements AccountService {
    
    

	@AutoWired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAll() {
    
    
        return accountDao.findAll();
    }

    @Override
    public Account findById(Integer accountId) {
    
    
        return accountDao.findById(accountId);
    }

    @Override
    public void insert(Account account) {
    
    
        accountDao.insert(account);
    }

    @Override
    public void update(Account account) {
    
    
        accountDao.update(account);
    }

    @Override
    public void delete(Integer accountId) {
    
    
        accountDao.delete(accountId);
    }
}

4. Create the persistence layer interface and implementation class

Persistence layer interface: IAccountDao.java

import org.example.domain.Account;

import java.util.List;

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

    // 根据id查询
    Account findById(Integer accountId);

    // 插入数据
    void insert(Account account);

    // 更新数据
    void update(Account account);

    // 根据Id删除数据
    void delete(Integer accountId);

}

Persistence layer implementation class: AccountDaoImpl.java

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.example.dao.IAccountDao;
import org.example.domain.Account;

import java.util.List;

/*
* 永久层实现类
* */
@Reopository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    
    
    @Autowired
    private QueryRunner queryRunner;

    @Override
    public List<Account> findAll() {
    
    
        try{
    
    
            return queryRunner.query("select *from account", new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findById(Integer accountId) {
    
    
        try{
    
    
            return queryRunner.query("select *from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

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

    @Override
    public void update(Account account) {
    
    
        try{
    
    
            queryRunner.update("update account set name = ?, money = ? where id = ?", account.getName(), account.getMoney(), account.getId());
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

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

5. Configuration file

Create a configuration file springConfig.java in the config package

@Configuration
@ComponentScan("org.example")
public class SpringConfig {
    
    
    // 配置QueryRunner对象同时注入容器
    @Bean("runner")
    public QueryRunner createQueryRunner(DataSource dataSource) {
    
    
        return new QueryRunner(dataSource);
    }

    // 配置Datasource数据源同时注入容器
    @Bean("dataSource")
    public DataSource createSource() {
    
    
        try {
    
    
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://121.41.229.122:3306/spring");
            ds.setUser("root");
            ds.setPassword("123456");
            return ds;
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

6. Test

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

insert image description here

Note: the default is a singleton object

Test if it is a singleton object

   // 测试是否为单例对象
    @Test
    public void testQueryRunner() {
    
    
        // 1、获取容器
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
        // 2、得到业务对象
        AccountService as = ac.getBean("accountService", AccountService.class);
        AccountService as2 = ac.getBean("accountService", AccountService.class);
        System.out.println(as == as2); // true
    }

Guess you like

Origin blog.csdn.net/qq_44660367/article/details/108170080