美文网首页
Spring IoC

Spring IoC

作者: 朱芮林 | 来源:发表于2019-03-04 22:35 被阅读0次

IoC容器

作用:管理所有bean及其相互间的依赖关系。
IoC两种设计模式:
反射:反射就是把java类中的各种成分映射成一个个的Java对象
工厂模式

把IoC容器当做一个工厂,在配置文件或注解中给出定义,然后利用反射技术,根据给出的类名生成相应的对象。对象生成的代码及对象之间的依赖关系在配置文件中定义,实现了解耦。

以MessageService为例
MessageService类

package com.spring.IoC;


public interface MessageService {
    String getMessage();
}

MessageServiceImpl类

package com.spring.IoC;


public class MessageServiceImpl implements  MessageService {
    private String username;
    private int age;
    public MessageServiceImpl(String username, int age) {
        this.username = username;
        this.age = age;
    }
    public String getMessage(){
        return "Hello World"+username+",age is "+age;
    }
}

MessagePrinter类

package com.spring.IoC;


public class MessagePrinter {
    final private MessageService service;
    public  MessagePrinter(MessageService service){
        this.service=service;
    }
    public void printMessage(){
        System.out.print(this. service.getMessage());
    }

}

MessageApp

package com.spring.IoC;

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

public class MessageApp {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context= new ClassPathXmlApplicationContext("spring.xml");
        MessagePrinter printer=context.getBean(MessagePrinter.class);
        printer.printMessage();
    }
}

beans(此处为spring.xml)

<bean id="messageServiceImpl" class="com.spring.IoC.MessageServiceImpl">
        <constructor-arg name="username" value="Jerry"/>
        <constructor-arg name="age" value="20"/>
   </bean>
    <bean id="messagePrinter" class="com.spring.IoC.MessagePrinter">
        <constructor-arg name="service" ref="messageServiceImpl"/>
    </bean>

结果为:


结果.png

相关文章

网友评论

      本文标题:Spring IoC

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