Spring-ioc-构造器注入

2018-07-06  本文已影响0人  gentel_liao

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>
上一篇下一篇

猜你喜欢

热点阅读