美文网首页
Spring-ioc-构造器注入

Spring-ioc-构造器注入

作者: gentel_liao | 来源:发表于2018-07-06 13:13 被阅读0次

    DAO接口

    IInjectionDao

    package com.spring.ioc.injection.dao;
    
    public interface IInjectionDAO {
        public void save(String arg);
    }
    

    Service接口

    IInjectionService

    package com.spring.ioc.injection.service;
    
    public interface IInjectionService {
        public void save(String arg);
    }
    
    

    实现类

    DAO

    IInjectionDaoImpl

    package com.spring.ioc.injection.dao;
    
    public class IInjectionDAOImpl implements IInjectionDAO {
    
        @Override
        public void save(String arg) {
            System.out.println("保存数据:" + arg);
        }
    }
    

    Service

    IInjectionServiceImpl

    package com.spring.ioc.injection.service;
    
    import com.spring.ioc.injection.dao.IInjectionDAO;
    
    public class IInjectionServiceImpl implements IInjectionService {
        //构造器注入--1
        private IInjectionDAO injectionDAO;
        //构造器注入--2
        public IInjectionServiceImpl(IInjectionDAO injectionDAO) {
            this.injectionDAO = injectionDAO;
        }
        //构造器注入--3
        public void setInjectionDAO(IInjectionDAO injectionDAO) {
            this.injectionDAO = injectionDAO;
        }
    
        @Override
        public void save(String arg) {
            injectionDAO.save(arg);
            System.out.println("设值注入:" + arg );
        }
    }
    
    

    Spring XML文件配置

    spring-injection

    <?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">
    
        <!--构造器注入 1 -->
        <bean id ="injectionService" class="com.spring.ioc.injection.service.IInjectionServiceImpl">
            <constructor-arg name="injectionDAO" ref="injectionDAO"></constructor-arg>
        </bean>
        <!--构造器注入 2 -->
        <bean id="injectionDAO" class="com.spring.ioc.injection.dao.IInjectionDAOImpl"></bean>
    
    </beans>
    

    相关文章

      网友评论

          本文标题:Spring-ioc-构造器注入

          本文链接:https://www.haomeiwen.com/subject/lhwvuftx.html