1, maven dependence
<?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.ly.spring</groupId> <artifactId>spring04</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>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.0.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> </project>
2, the entity class
package com.ly.spring.domain; import java.io.Serializable; public class Account implements Serializable { private Integer id; private Integer uid; private double money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", uid=" + uid + ", money=" + money + '}'; } }
3, Service Interface
package com.ly.spring.service; import com.ly.spring.domain.Account; import java.sql.SQLException; import java.util.List; public interface IAccountService { public List<Account> findAll() throws SQLException; public Account findOne(Integer id) throws SQLException; public void save(Account account) throws SQLException; public void update(Account account) throws SQLException; public void delete(Integer id) throws SQLException; }
4, Service implementation class
package com.ly.spring.service.impl; import com.ly.spring.dao.IAccountDao; import com.ly.spring.domain.Account; import com.ly.spring.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.List; @Service("accountService") public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; public List<Account> findAll() throws SQLException { return accountDao.findAll(); } @Override public Account findOne(Integer id) throws SQLException { return accountDao.findOne(id); } @Override public void save(Account account) throws SQLException { accountDao.save(account); } @Override public void update(Account account) throws SQLException { accountDao.update(account); } @Override public void delete(Integer id) throws SQLException { accountDao.delete(id); } }
5, Dao Interface
package com.ly.spring.dao; import com.ly.spring.domain.Account; import java.sql.SQLException; import java.util.List; public interface IAccountDao { public List<Account> findAll() throws SQLException; public Account findOne(Integer id) throws SQLException; public void save(Account account) throws SQLException; public void update(Account account) throws SQLException; public void delete(Integer id) throws SQLException; }
6, Dao implementation class
package com.ly.spring.dao.impl; import com.ly.spring.dao.IAccountDao; import com.ly.spring.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.sql.SQLException; import java.util.List; @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Autowired private QueryRunner queryRunner; public List<Account> findAll() throws SQLException { return queryRunner.query("select * from account",new BeanListHandler<Account>(Account.class)); } @Override public Account findOne(Integer id) throws SQLException { return queryRunner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id); } @Override public void save(Account account) throws SQLException { queryRunner.update("insert into account(uid,money) values(?,?)",account.getUid(),account.getMoney()); } @Override public void update(Account account) throws SQLException { queryRunner.update("update account set money = ? where id = ?",account.getMoney(),account.getId()); } @Override public void delete(Integer id) throws SQLException { queryRunner.update("delete from account where id = ?",id); } }
7, jdbc resource file
jdbc.url = jdbc:mysql://localhost:3306/db01
jdbc.driver = com.mysql.jdbc.Driver
jdbc.username = root
jdbc.password = root
8, spring main configuration class
Package com.ly.spring.config; Import org.springframework.context.annotation *. ; // @Configuration: for the configuration of such a class mark / ** * @Configuration Note: * 1, such as when new AnnotationConfigApplicationContext () into the parameter types, annotation may be omitted @Configuration * 2, but if such is not the configuration class new AnnotationConfigApplicationContext () into parameters of type (JdbcConfig.java), * is introduced and the manner and configuration class is @ComponentScan non @Import, annotations can not be omitted @Configuration * 3, if the configuration class (JdbcConfig.java) introduced by @Import, configuration class were introduced annotations may be omitted @Configuration * 4, @ ComponentScan ({ " com. ly.spring "," xx.xxx "}) you can configure multiple * / @Configuration // @ComponentScan: a package scanning annotation specifies spring @ComponentScan (" com.ly.spring " ) //@PropertySource: Specifies the external properties file @PropertySource ( "CLASSPATH: the db.properties" ) // @Import: introducing a further configuration class / ** * @Import Description * 1, if desired, the introduced class may be scanned through @ComponentScan , and the class has @Configuration annotations do not require this configuration @Import annotation category is introduced * 2, using @Import introduced configuration class, the configuration can be omitted @Configuration class annotations * 3, @ Import ({JdbcConfig.class , xxx .class}) may be introduced into a plurality * / @Import (JdbcConfig. class ) public class SpringConfiguration { }
9, jdbc configuration class
package com.ly.spring.config; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import javax.sql.DataSource; //@Configuration:用于标记此类为配置类 @Configuration public class JdbcConfig { //@Value: for reading the resource file with the specified key value @value ( "jdbc.url $ {}" ) Private String the jdbcUrl; @value ( "jdbc.driver $ {}" ) Private String jdbcDriver; @value ( "$ {} jdbc.username" ) Private String username; @Value ( "$ {} jdbc.password" ) Private String password; // @Bean method for creating a type of return value of the spring container bean, created the default name is a method bean id // when configured @Bean i.e. attribute specifies the name of the created corresponding bean id @Bean @ @Scope: Specifies the bean scope created, a default single embodiment @Scope ( "singleton" ) //When the method and there is no parameter specifying the bean @Qualifier annotation id, the vessel will automatically follow from the spring @Autowired annotation way to inject bean // when the process parameters and there have @Qualifier annotation specifying the bean id, will the specified id to find the corresponding spring container the bean public QueryRunner getQueryRunner (@Qualifier ( "the dataSource" ) the DataSource the dataSource) { return new new QueryRunner (the dataSource); } // name created bean id specified in the spring container @Bean (name = "the dataSource" ) public the DataSource getDataSource () { the try { ComboPooledDataSource ComboPooledDataSource = new new ComboPooledDataSource (); comboPooledDataSource.setDriverClass (jdbcDriver); comboPooledDataSource.setJdbcUrl (the jdbcUrl); comboPooledDataSource.setUser(username); comboPooledDataSource.setPassword(password); return comboPooledDataSource; }catch (Exception e) { throw new RuntimeException(e); } } }
10, the test class
package com.ly.spring.test; import com.ly.spring.config.JdbcConfig; import com.ly.spring.config.SpringConfiguration; import com.ly.spring.domain.Account; import com.ly.spring.service.IAccountService; import org.apache.commons.dbutils.QueryRunner; import org.junit.Before; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import javax.sql.DataSource; import java.sql.SQLException; import java.util.List; public class MainTest { privateContext AnnotationConfigApplicationContext; Private IAccountService AccountService; @Before public void the init () { // Get the container through the spring annotation // can specify the plurality of configuration classes // context = new new AnnotationConfigApplicationContext (SpringConfiguration.class, JdbcConfig.class); context = new new AnnotationConfigApplicationContext (SpringConfiguration. class ); AccountService = context.getBean ( "AccountService", IAccountService. class ); } @Test public void testScope () { DataSource dataSource1 = context.getBean("dataSource", DataSource.class); DataSource dataSource2 = context.getBean("dataSource", DataSource.class); System.out.println(dataSource1 == dataSource2); QueryRunner queryRunner1 = context.getBean("getQueryRunner", QueryRunner.class); QueryRunner queryRunner2 = context.getBean("getQueryRunner", QueryRunner.class); System.out.println(queryRunner1); System.out.println(queryRunner1 == queryRunner2); public @Test } void findAll() throws SQLException { List<Account> accounts = accountService.findAll(); System.out.println(accounts); } @Test public void findOne() throws SQLException { Account account = accountService.findOne(3); System.out.println(account); } @Test public void save() throws SQLException { Account account = new Account(); account.setUid(52); account.setMoney(6000); accountService.save(account); } @Test public void update() throws SQLException { Account account = new Account(); account.setId(5); account.setMoney(100000); accountService.update(account); } @Test public void delete() throws SQLException { accountService.delete(5); } }
11, the integration of supplementary spring junit, amend as follows:
11.1, the introduction of spring-test jar package
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> <scope>test</scope> </dependency>
11.2, using the main alternative method @RunWith annotated in the test class junit
11.3, the configuration file specifies the location of the spring or spring-based configuration used in the test class annotation @ContextConfiguration
package com.ly.spring.test; import com.ly.spring.config.SpringConfiguration; import com.ly.spring.domain.Account; import com.ly.spring.service.IAccountService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.SQLException; import java.util.List; //@RunWith:用于替换junit的main方法 @RunWith(SpringJUnit4ClassRunner.class ) // @ContextConfiguration: the configuration file specifies the location of the spring or spring configuration type / ** * @ContextConfiguration Description * 1, locations specify a position locations spring configuration file = "CLASSPATH: bean.xml" * 2, classes spring configuration is used to specify the class * / @ContextConfiguration (classes = SpringConfiguration. class ) public class MainTest { @Autowired Private IAccountService AccountService; @Test public void the findAll () throws SQLException { List <the Account> Accounts = accountService.findAll (); System.out.println (accounts); } @Test public void findOne() throws SQLException { Account account = accountService.findOne(3); System.out.println(account); } @Test public void save() throws SQLException { Account account = new Account(); account.setUid(52); account.setMoney(6000); accountService.save(account); } @Test public void update() throws SQLException { Account account = new Account(); account.setId(5); account.setMoney(100000); accountService.update(account); } @Test public void delete() throws SQLException { accountService.delete(5); } }
11.4, SpringJUnit4ClassRunner requires JUnit 4.12 or higher error resolved
Junit need to upgrade version 4.12 and above
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>