首页 > 编程语言 > 详细

我爱Java系列---【基于注解的 IOC 配置】

时间:2019-07-01 22:50:48      阅读:106      评论:0      收藏:0      [点我收藏+]

总结:

注解和配置文件的区别:

一、环境搭建

  1.创建 maven 工程quickstart,并导入坐标

pom.xml 中的依赖:
<dependencies>
<!-- junit单元测试 -->

<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封装了对JDBC的操作,简化了JDBC操作,可以少写代码。
org.apache.commons.dbutils
DbUtils 关闭链接等操作
QueryRunner 进行查询的操作
org.apache.commons.dbutils.handlers 处理结果集

-->
  <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 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.编写持久层代码

//定义接口
public interface AccountDao { //1.增加账户 public int save(Account account); //2.根据id查询账户 public Account findById(int id); }
//编写实现类

@Component("accountDao") //把下面这个类放到spring容器中,谁需要就用@Resource(name="accountDao")去取
public class AccountDaoImpl implements AccountDao {

@Resource(name="queryRunner") //1.从spring容器中取出queryRunner对象,当你使用注解的方式注入对象,不需要写set方法,因为配置文件属性注入方式底层采用调用setter方法,
而注解方式底层采用暴力反射
//2.此处应当注意,queryRunner来自第三方,配置文件中的声明不可省略,连接数据库的声明也不可省略
//3.注意:@Resource(name="queryRunner") 必须要写在声明变量之前,即下面这句话之前,private QueryRunner queryRunner;的前面,否则报错
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.编写业务层代码

//定义接口
public interface AccountService {

    //1.增加账户
    public int save(Account account);

    //2.根据id查询账户信息
    public Account findById(int id);
}
//编写实现类
@Component("accountService ") //把下面这个类放到spring容器中,谁需要就用@Resource(name="accountService ")去取 public class AccountServiceImpl implements AccountService {

@Resource(name="accountService ") //1.从spring容器中取出accountService对象,当你使用注解的方式注入对象,不需要写set方法,因为配置文件属性注入方式底层采用调用setter方法,
而注解方式底层采用暴力反射
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); } }

二、创建配置文件

1.创建配置文件并导入约束

<?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>

三、测试代码

 

@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("添加账户失败"); } }

 //2.根据id查询账户信息
@Test public void testFindById(){
Account accountById = accountService.findById(2);
System.out.println(accountById);
}
}

 

至此,增和查的功能已经完成,删改功能同理可得。

 

我爱Java系列---【基于注解的 IOC 配置】

原文:https://www.cnblogs.com/hujunwei/p/11117103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!