spring 的依赖注入

spring 的依赖注入

依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。
我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。
ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

构造函数注入

使用的标签:constructor-arg
标签出现的位置:bean标签的内部
标签中的属性
    type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
    index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始
    name:用于指定给构造函数中指定名称的参数赋值                                        常用的
    =============以上三个用于指定给构造函数中哪个参数赋值===============================
    value:用于提供基本类型和String类型的数据
    ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象

优势:
    在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功。
弊端:
    改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。
示例代码:

service实现类代码

public class AccountServiceImpl implements IAccountService {
    private String name;
    private Integer age;
    private Date nowTime;

    public AccountServiceImpl(String name, Integer age, Date nowTime) {
        this.name = name;
        this.age = age;
        this.nowTime = nowTime;
    }
    public void saveAccount() {
        //业务层调用持久层
        System.out.println("保存了"+"姓名"+name+"年龄"+age+"保存时间"+nowTime);
    }
}

bean标签

<bean id="accountService" class="com.tiger.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="Aaron_Kitty"/>
        <constructor-arg name="age" value="18"/>
        <constructor-arg name="nowTime" ref="now"/>
    </bean>
    <bean id="now" class="java.util.Date"/>

set 方法注入

涉及的标签:property
出现的位置:bean标签的内部
标签的属性
    name:用于指定注入时所调用的set方法名称
    value:用于提供基本类型和String类型的数据
    ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
优势:
    创建对象时没有明确的限制,可以直接使用默认构造函数
弊端:
    如果有某个成员必须有值,则获取对象是有可能set方法没有执行。

示例代码:

<bean id="accountService2" class="com.tiger.service.impl.AccountServiceImpl2">
        <property name="name" value="111"/>
        <property name="age" value="12"/>
        <property name="nowTime" ref="now"/>
    </bean>
public class AccountServiceImpl2 implements IAccountService {
    private String name;
    private Integer age;
    private Date nowTime;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setNowTime(Date nowTime) {
        this.nowTime = nowTime;
    }

    public void saveAccount() {
        //业务层调用持久层
        System.out.println("保存了"+"姓名"+name+"年龄"+age+"保存时间"+nowTime);
    }
}

复杂类型的注入/集合类型的注入

用于给List结构集合注入的标签:
    list array set
用于个Map结构集合注入的标签:
    map  props
结构相同,标签可以互换

示例代码:

ublic class AccountServiceImpl3 implements IAccountService {
    private String[] strings;
    private Map<String,String> map;
    private Set<String> set;
    private Properties properties;

    public void setStrings(String[] strings) {
        this.strings = strings;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void saveAccount() {
        System.out.println(Arrays.toString(strings));
        System.out.println(map);
        System.out.println(set);
        System.out.println(properties);
    }
}
 <bean id="accountService3" class="com.tiger.service.impl.AccountServiceImpl3">
        <property name="strings">
           <array>
               <value>AAA</value>
               <value>BBB</value>
               <value>CCC</value>
           </array>
        </property>
        <property name="map">
            <map>
                <entry key="QQQ" value="WWW"/>
                <entry key="sss" value="jjj"/>
            </map>
        </property>
        <property name="properties">
            <props>
                <prop key="qqq">qqq</prop>
                <prop key="www">www</prop>
            </props>
        </property>
        <property name="set">
            <set>
                <value>1111111</value>
            </set>
        </property>
    </bean>

实战代码

Service代码

public interface IAccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return id
     */
    Account findById(Integer id);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param id
     */
    void deleteAccount(Integer id);
}
public class AccountServiceImp implements IAccountService {
    private IAccountDao accountDao;

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

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

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

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

Dao

public interface IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return id
     */
    Account findById(Integer id);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param id
     */
    void deleteAccount(Integer id);
}
public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner;

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

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

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

    public void saveAccount(Account account) {
        try {
            runner.update("insert into account_two (name,money) values(?,?)",account.getName(),account.getMoney());
            //runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update("update account_two set name =?,money=?,where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
           e.printStackTrace();
        }
    }

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

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">
    <!--配置service对象-->
    <bean id="accountService" class="com.tiger.service.impl.AccountServiceImp">
        <!--注入dao对象-->
        <property name="accountDao" ref="dao"/>
    </bean>
    <bean id="dao" class="com.tiger.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="datasourse"/>
    </bean>
    <!--配置数据源-->
    <bean id="datasourse" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>

</beans>

导入的依赖

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>

test代码

public class AccountServiceTest {
    private IAccountService as;
    private ClassPathXmlApplicationContext ac;
    @Before
    public void init(){
        ac = new ClassPathXmlApplicationContext("bean.xml");
        as = ac.getBean("accountService", IAccountService.class);
    }
    @Test
    public void testFindAll() {
        List<Account> allAccount = as.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne() {
        Account byId = as.findById(1);
        System.out.println(byId);
    }
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("学习");
        account.setMoney(12345);
        //3.执行方法
        as.saveAccount(account);
    }
    @Test
    public void testUpdate() {
        Account account = as.findById(1);
        account.setMoney(23456f);
        account.setName("dsd");
        as.updateAccount(account);
    }
    @Test
    public void testDelete() {
            as.deleteAccount(1);
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值