Spring代码实例系列-02:松耦合loose coupling(通过xml文件以默认的方式进行setter注入)

超级通道:Spring代码实例系列-绪论
本节主要侧重展示Spring框架中的松耦合,简单应用了以下技术:
1. 注入bean
2. spring的xml配置文件
3. setter注入
4. 松耦合

1.目录

project
    \---src
        \---main
            \---java
            |   \---pers
            |       \---hanchao
            |           \---loosecoupling
            |               \---App.java
            |               \---MyFavoriteFruit.java
            |               \---Fruit.java  
            |               \---Apple.java  
            |               \---Orange.java 
            \---resources
                \---spring-config
                    \---spring-loosecoupling.xml

2.App.java

package pers.hanchao.loosecoupling;

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

/**
 * <p>spring松耦合示例:通过配置xml中注入的bean,实现注入bean的灵活控制</p>
 * @author hanchao 2018/1/7 12:32
 **/
public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config/spring-loosecoupling.xml");
        MyFavoriteFruit myFavoriteFruit = (MyFavoriteFruit) context.getBean("myFavoriteFruit");
        myFavoriteFruit.showMyFavoriteFruit();
    }
}

3.spring-loosecoupling.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="myFavoriteFruit" class="pers.hanchao.loosecoupling.MyFavoriteFruit">
        <property name="fruit" ref="apple"/>
    </bean>

    <bean id="apple" class="pers.hanchao.loosecoupling.Apple"/>
    <bean id="orange" class="pers.hanchao.loosecoupling.Orange"/>
</beans>

4.MyFavoriteFruit.java

package pers.hanchao.loosecoupling;

public class MyFavoriteFruit {
    private Fruit fruit;

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

    public void showMyFavoriteFruit(){
        System.out.println("My favorite fruit is " + this.fruit.showName());
    }
}

5.Fruit.java

package pers.hanchao.loosecoupling;

public interface Fruit {
    public String showName();
}

6.Apple.java

package pers.hanchao.loosecoupling;

public class Apple implements Fruit{

    @Override
    public String showName() {
        return "apple";
    }
}

7.Orange.java

package pers.hanchao.loosecoupling;

public class Orange implements Fruit {
    @Override
    public String showName() {
        return "orange";
    }
}

8.result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值