SpringBoot - IOC 记录

摘自 Spring Boot笔记十:IOC控制反转
记录了部分自己需要的内容

这篇文章也比较清晰地表述了Spring IOC和DI:浅谈对Spring IOC以及DI的理解

例子

先创建一个类

public class HelloWorld {
    private String userName;
    public void  setUserName(String userName){
        this.userName=userName;
    }
    public void sayHello(){
        System.out.println("Hello World " + userName);
    }
}

然后配置一个xml配置文件:applicationContext.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="helloWorld" class="com.vae.springboot.bean.HelloWorld">
        <property name="userName" value="许嵩"></property>
    </bean>

</beans>

上述配置文件也可以从其他文件中引入部分配置,如加入以下内容:

<import resource="classpath:com.vae.springboot.bean.HelloWorld.xml"></import>

然后在Test里面,HelloWorld需要有Setter实现

    @Test
    public void sayHelloIOC(){
        HelloWorld helloWorld=null;
        //--------------------IOC开始了-------------------
        //1.从classpath路径去寻找配置文件,加载我们的配置
        Resource resources= new ClassPathResource("applicationContext.xml");
        //2.加载配置文件之后,创建IOC容器
        BeanFactory factory=new XmlBeanFactory(resources);
        //3.从Spring IOC容器中获取指定名称的对象
        helloWorld= (HelloWorld) factory.getBean("helloWorld");
        //--------------------IOC结束了---------------------
        helloWorld.sayHello();
    }

另一种方法是使用@Autowired注解完成

@SpringBootTest
@ContextConfiguration("classpath:applicationContext.xml")
class ApplicationContextApplicationTests {
    private HelloWorld helloWorld;
    @Test
    public void sayHelloIOCNB(){
        helloWorld.sayHello();
    }
}
posted @ 2020-10-18 17:51  wunai006  阅读(82)  评论(0)    收藏  举报