spring ioc认识

spring之ioc(Inverion of Control),即控制反转。我现在所知道的有四种注入方式,

1. set注入;

2. 构造函数注入;

3. 接口注入;

4. 自动依赖注入。

定义GeLi 类

public class GeLi {
    
    private String name;
    
    public GeLi(){
        
    }
    
    public GeLi(String name){
        this.name = name;
    }
    
    //在剧本中该角色的台词
    public void responSay(String message){
        System.out.println(this.name+": "+message);
    }
}

GuoFuCheng 类

public class GuoFuCheng extends GeLi{
    
    public GuoFuCheng(){
        
    }
    
    public GuoFuCheng(String name){
        super(name);
    }
}

ZhangBoZhi 类

public class ZhangBoZhi extends GeLi{
    
    public ZhangBoZhi(){
        
    }
    
    public ZhangBoZhi(String name){
        super(name);
    }
}

MovieAction 类

public class MovieAction {
    
    //具体演员
    private GeLi geli;
    
    public MovieAction(){
        
    }
    
    public MovieAction(GeLi geli){
        this.geli = geli;
    }
    
    public void startMovie(){
        //演员开始表演
        geli.responSay("墨者革离");
        
    }

    public void setGeli(GeLi geli) {
        this.geli = geli;
    }
    
}

Director 类

public class Director {
    
    public void director(){
        //GeLi geli = new ZhangBoZhi("柏芝");
        //MovieAction m = new MovieAction(geli);
        //m.startMovie();
        //在bean.xml中已配置好GeLi角色由谁来演
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        MovieAction m = (MovieAction) context.getBean("movieAction");
        m.startMovie();
    }
    
}

Test 类

public class Test {
    
    public static void main(String[] args) {
        new Director().director();
    }

}

在bean.xml 中配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
       
       <bean id="GuoFuCheng" class="com.admin.ioc.GuoFuCheng">
           <constructor-arg value="郭富城"></constructor-arg>
       </bean>
       
       <bean id="zhangbozhi" class="com.admin.ioc.ZhangBoZhi">
           <constructor-arg value="柏芝"></constructor-arg>
       </bean>
       
       <bean id="movieAction" class="com.admin.ioc.MovieAction">
           <property name="geli" ref="GuoFuCheng"></property>
       </bean>
       
</beans>

运行结果:郭富城: 墨者革离

原文地址:https://www.cnblogs.com/dzyBlog/p/5337025.html