Spring注入方式

1:设值注入

  spring容器使用属性的setter方法来注入被依赖的实例(使用最多)

  Person接口

package com.lee.bean;

public interface Person {

    public void eat();

}

  Fruit接口

package com.lee.bean;

public interface Fruit {

    public void description();

}

  Person的实现类

package com.lee.bean.impl;

import com.lee.bean.Fruit;
import com.lee.bean.Person;

public class XiaoMing implements Person {

    private Fruit fruit;

    public void eat() {

        fruit.description();
        System.out.println("yummy!");
    }

    public Fruit getFruit() {
        return fruit;
    }

    public void setFruit(Fruit fruit) {
        this.fruit = fruit;
    }

}

  Fruit的实现类

package com.lee.bean.impl;

import com.lee.bean.Fruit;

public class Apple implements Fruit {

    public void description() {

        System.out.print("this is an apple! ");

    }

}

  spring的配置文件bean.xml(classpath下)

<?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="xiaoMing" class="com.lee.bean.impl.XiaoMing">
        <property name="fruit" ref="apple"></property>
    </bean>

    <bean id="apple" class="com.lee.bean.impl.Apple"></bean>

</beans>

测试类

package com.lee.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lee.bean.impl.XiaoMing;

public class BeanTest {

    public static void main(String[] args) {

        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        XiaoMing xiaoMing = ac.getBean("xiaoMing", XiaoMing.class);

        xiaoMing.eat();

    }

}

  运行结果,在控制台打印出

 

this is an apple! yummy!

  2:构造注入

  修改XiaoMing.java

package com.lee.bean.impl;

import com.lee.bean.Fruit;
import com.lee.bean.Person;

public class XiaoMing implements Person {

    private Fruit fruit;

    public void eat() {

        fruit.description();
        System.out.println("yummy!");
    }

    public XiaoMing(Fruit fruit) {
        this.fruit = fruit;
    }

}

  修改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="xiaoMing" class="com.lee.bean.impl.XiaoMing">
        <constructor-arg ref="apple" />
    </bean>

    <bean id="apple" class="com.lee.bean.impl.Apple"></bean>

</beans>
原文地址:https://www.cnblogs.com/harryV/p/3728060.html