Spring学习笔记(三)

Spring的注解注入

IAccountDao.java

package com.how2java.dao;

public interface IAccountDao {
    public void saveAccount();
}

AccountDaoImpl1.java

package com.how2java.dao.impl;

import com.how2java.dao.IAccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * 账户的持久层实现类
 */
//@Component("accountDao1")
@Repository("accountDao1")
public class AccountDaoImpl1 implements IAccountDao{
    @Override
    public void saveAccount() {
        System.out.println("保存了账户111");
    }
}

AccountDaoImpl2.java

package com.how2java.dao.impl;

import com.how2java.dao.IAccountDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

/**
 * 账户的持久层实现类
 */
//@Component("accountDao2")
@Repository("accountDao2")
public class AccountDaoImpl2 implements IAccountDao{
    @Override
    public void saveAccount() {
        System.out.println("保存了账户222");
    }
}

IAccountService.java

package com.how2java.service;

public interface IAccountService {
    public void saveAccount();
}

AccountServiceImpl.java

package com.how2java.service.impl;

import com.how2java.dao.IAccountDao;
import com.how2java.service.IAccountService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 账户的业务层实现类
 *
 * XML配置:
 * <bean id="accountService" class="com.how2java.service.impl.AccountServiceImpl" scope="" init-method="" destroy-method="">
 *     <property name="" value="" ref=""></property>
 *     </bean>
 *
 * 创建对象的部分:对应XML文件中的bean标签。
 *     Component:
 *         作用:把当前类对象存入Spring容器中。
 *         属性:value用于指定bean标签的id,默认值(不写)为当前类名,且首字母改小写。
*      Controller:一般用于表现层。
 *     Service:一般用于业务层。
 *     Repository:一般用于持久层。
 *     这三个的作用和属性与Component相同,是Spring框架提供的三层架构注解。
 *
 * 注入数据的部分:对应XML文件中bean标签内的property标签。
 *     Autowired:
 *         作用:自动按照数据类型注入。
 *             ①只要容器中有唯一的bean对象类型和要注入的变量类型匹配,就可以注入成功。
 *             ②如果容器中没有任何bean的类型和要注入的变量类型匹配,就会注入失败。
 *             ③如果容器中有多个bean的类型和要注入的变量类型匹配,就需要Qualifier注解。
 *         出现位置:可以是成员变量,也可以是方法。
*      Qualifier:
 *         作用:在按照数据类型注入的基础上再按变量名称注入。在给类成员注入时不能单独使用(配合Autowired),但在给方法参数注入时可以使用。
 *         属性:value指定注入bean对象的id。
 *     Resource:
 *         作用:直接按照bean对象的id注入。
 *         属性:name指定注入bean对象的id。
 *     这三个注解只适用于bean类型的数据注入,而基本类型和String类型的数据无法实现注入。
 *     另外,集合类型数据注入只能使用XML文件实现注入。
 *     Value:
 *         作用:基本数据类型和String的数据注入。
 *         属性:value指定注入数据的值。支持spEL表达式,写法为${表达式}。
 *
 * 改变作用范围的部分:对应XML文件中bean标签中scope属性。
 *     Scope:
 *         作用:指定bean的作用范围。
 *         属性:value指定范围的值。常用:singleton,prototype。
 *
 * 与生命周期相关的部分:对应XML文件中bean标签中init-method和destroy-method属性。
 *     PreDestroy:
 *         作用:指定销毁方法。
 *     PostConstruct
 *         作用:指定初始化方法。
 */
@Service("accountService")
//@Component
//@Component(value = "accountService")
//@Component("accountService")
//@Scope("prototype")
public class AccountServiceImpl implements IAccountService {

//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao1")
    private IAccountDao accountDao;

    @PostConstruct
    public void init() {
        System.out.println("初始化方法执行了");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("销毁方法执行了");
    }

    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

Client.java

package com.how2java.ui;

import com.how2java.dao.IAccountDao;
import com.how2java.service.IAccountService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * 模拟一个表现层,调用业务层
 */
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as = (IAccountService) ac.getBean("accountService");
//        IAccountDao ad = ac.getBean("accountDao", IAccountDao.class);
//        System.out.println(as);
//        System.out.println(ad);
//        System.out.println(as==ad);

        as.saveAccount();
    }
}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--告知Spring在创建容器时要扫描的包,
    所需要的标签不是在bean标签的约束中,而是一个名为context的名称空间和约束中。-->
    <context:component-scan base-package="com.how2java"></context:component-scan>
</beans>

在这里插入图片描述

基于XML的IOC案例

Account.java

package com.how2java.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 +
                '}';
    }
}

IAccountDao.java

package com.how2java.dao;

import com.how2java.domain.Account;

import java.util.List;

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

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findById(Integer id);

    /**
     * 保存账户
     * @param account
     */
    void save(Account account);

    /**
     * 更新账户
     * @param account
     */
    void update(Account account);

    /**
     * 删除账户
     * @param id
     */
    void delete(Integer id);
}

AccountDaoImpl.java

package com.how2java.dao.impl;

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

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao{

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

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

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

    @Override
    public void save(Account account) {
        try{
            runner.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{
            runner.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 id) {
        try{
            runner.update("delete from account where id = ?", id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

IAccountService.java

package com.how2java.service;

import com.how2java.domain.Account;

import java.util.List;

/**
 * 账户的业务层接口
 */
public interface IAccountService {
    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAll();

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findById(Integer id);

    /**
     * 保存账户
     * @param account
     */
    void save(Account account);

    /**
     * 更新账户
     * @param account
     */
    void update(Account account);

    /**
     * 删除账户
     * @param id
     */
    void delete(Integer id);
}

AccountServiceImpl.java

package com.how2java.service.impl;

import com.how2java.dao.IAccountDao;
import com.how2java.domain.Account;
import com.how2java.service.IAccountService;

import java.util.List;

/**
 * 业务层的实现类
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

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

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

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

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

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

bean.xml

<?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">
    <!--配置业务层对象-->
    <bean id="accountService" class="com.how2java.service.impl.AccountServiceImpl">
        <!--注入持久层对象-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--持久层对象-->
    <bean id="accountDao" class="com.how2java.dao.impl.AccountDaoImpl">
        <!--注入QueryRunner对象-->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner对象-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入连接信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>
    </bean>

</beans>

TestAccount.java

package com.how2java;

import com.how2java.domain.Account;
import com.how2java.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用junit测试配置
 */
public class TestAccount {

    @Test
    public void testFindAll() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService) ac.getBean("accountService");
        List<Account> accounts = as.findAll();
        for(Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService) ac.getBean("accountService");
        Account account = as.findById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService) ac.getBean("accountService");
        Account account = new Account();
        account.setName("ddd");
        account.setMoney(1000F);
        as.save(account);
    }

    @Test
    public void testUpdate() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService) ac.getBean("accountService");
        Account account = new Account();
        account.setId(4);
        account.setName("test");
        as.update(account);
    }

    @Test
    public void testDelete() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as = (IAccountService) ac.getBean("accountService");
        as.delete(4);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring是一个开源的Java框架,用于构建企业级应用程序。它提供了一种轻量级的、非侵入式的开发方式,通过依赖注入和面向切面编程等特性,简化了Java应用程序的开发过程。 以下是关于Spring学习的一些笔记: 1. IoC(控制反转):Spring通过IoC容器管理对象的创建和依赖关系的注入。通过配置文件或注解,将对象的创建和依赖关系的维护交给Spring容器来管理,降低了组件之间的耦合度。 2. DI(依赖注入):Spring通过依赖注入将对象之间的依赖关系解耦。通过构造函数、Setter方法或注解,将依赖的对象注入到目标对象中,使得对象之间的关系更加灵活和可维护。 3. AOP(面向切面编程):Spring提供了AOP的支持,可以将与业务逻辑无关的横切关注点(如日志、事务管理等)从业务逻辑中分离出来,提高了代码的可重用性和可维护性。 4. MVC(模型-视图-控制器):Spring提供了一个MVC框架,用于构建Web应用程序。通过DispatcherServlet、Controller、ViewResolver等组件,实现了请求的分发和处理,将业务逻辑和视图展示进行了分离。 5. JDBC和ORM支持:Spring提供了对JDBC和ORM框架(如Hibernate、MyBatis)的集成支持,简化了数据库访问的操作,提高了开发效率。 6. 事务管理:Spring提供了对事务的支持,通过声明式事务管理和编程式事务管理,实现了对数据库事务的控制和管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值