I love Java-based series --- [IOC] annotation configuration

to sum up:

The difference between notes and configuration files:

First, set up the environment

  1. Create a maven project quickstart, and import coordinates

pom.xml Dependence:
<dependencies>
<-! Junit unit test -> 

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring整合测试类-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>

<!-- spring框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- dbutils
DBUtils encapsulates the JDBC operation simplifies JDBC operations, write less code.
org.apache.commons.dbutils
DbUtils close links and other operations
QueryRunner operating query
org.apache.commons.dbutils.handlers result set

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

<!-- mysql驱动-->
  <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>

2. Create a database and write entity class

// Create database 
Create Table Account ( ID int AUTO_INCREMENT Primary Key , name VARCHAR ( 32 ), password VARCHAR ( 32 ), Money int );
//编写实体类
public class Account { private long id; private String name; private String password; private long money; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public long getMoney() { return money; } public void setMoney(long money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", money=" + money + '}'; } }

3. Write persistence layer of code

// definition of the interface 
public interface AccountDao { // 1. accounts increased public int Save (the Account Account); // 2. The access subscription id public the findById the Account ( int id);}
// write implementation class 

@Component ( "AccountDao") // spring into the following class vessel, who needs to use @Resource (name = " AccountDao pick")
public class AccountDaoImpl the implements AccountDao {

@Resource (name = " queryRunner") //. 1. remove the container from the spring queryRunner object, when the injection mode annotation objects you use, no need to write the set method, injection method because the profile properties using the underlying setter method is called,
and the use of violence underlying reflective mode annotations
// 2 should be noted here, queryRunner from third parties, the configuration file can not be omitted in the statement, the statement database connection can not be omitted // 3. Note: @Resource (name = "queryRunner" ) must be written in the variable declaration before, i.e., before the following sentence, private queryRunner queryRunner; front, otherwise an error Private queryRunner queryRunner; / * public void

setQueryRunner(QueryRunner queryRunner) { this.queryRunner = queryRunner; }*/ //1.增加账户 public int save(Account account){ String sql ="insert into account values (null,?,?,?) "; try { return queryRunner.update(sql,account.getName(),account.getPassword(),account.getMoney()); } catch (SQLException e) { throw new RuntimeException(e); } } //2.根据id查询账户信息 @Override public Account findById(int id) { String sql ="select * from account where id=?"; try { return queryRunner.query(sql,new BeanHandler<>(Account.class),id); } catch (SQLException e) { throw new RuntimeException(e); } } }

4. Preparation of service level code

// definition of the interface
 public interface the AccountService { // 1. accounts increased public int Save (the Account Account); // 2. The access subscription information id public the findById the Account ( int id);}

    
// write implementation class 
@Component ( "AccountService") // spring into the following class vessel, who needs to use @Resource (name = " AccountService pick") public class AccountServiceImpl the implements the AccountService {

@Resource (name = "AccountService")  //. 1. Remove the container from the spring AccountService objects, when the injection mode annotation objects you use, no need to write the set method, injection method because the profile properties using the underlying setter method is called, 
and annotated how the underlying reflective use of violence
private AccountDao accountDao;
/*public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } */

//1.增加账户

@Override
public int save(Account account) { return accountDao.save(account); }

//2.根据id查询账户
@Override
public Account findById(int id) { return accountDao.findById(id); } }

Second, create a profile

1. Create the configuration file and import constraints

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--分析:service - dao - queryRunner - dateSource,从后往前配 --> <!--1.配置dateSource--> <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="jdbc:mysql:///heima?characterEncoding=utf-8"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--2.配置queryRunner--> <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"> <constructor-arg name="ds" ref="dateSource"></constructor-arg> </bean>  <!-- <!--3.配置AccountDao--> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"> <property name="queryRunner" ref="queryRunner"/> </bean> <!--4.配置AccountService,并解决依赖注入--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <property name="accountDao" ref="accountDao"/> </bean>--> </beans>

Third, the test code

 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:beans.xml")
public class AccountTest { @Autowired private AccountService accountService; 
//1.增加账户

@Test public void testSave() {
Account account = new Account();
account.setId(2); account.setName("亚瑟");
account.setPassword("yuji");
account.setMoney(3000);
int i = accountService.save(account);
if (i == 1) { System.out.println("添加账户成功"); } else{System.out.println ( "Add Account failed" );}}

 // The id check account information
@Test public void testFindById(){
Account accountById = accountService.findById(2);
System.out.println(accountById);
}
}

 

Thus, by and check function has been completed, altered function Similarly available.

 

Guess you like

Origin www.cnblogs.com/hujunwei/p/11117103.html