Spring Ioc容器

Ioc也称为依赖注入/控制反转,Ioc容器主要负责实例化、配置和组装Bean,开发人员不在须要写Bean的实例化代码,简化代码的同时能够下降Bean之间的耦合度。Ioc的顶级接口是org.springframework.beans.factory.BeanFactory,大部分状况下咱们会用到它的子接口org.springframework.context.ApplicationContext 该接口提供了更丰富的功能。java

使用Xml配置Bean并启动Spring容器spring

  1. 首先建立一个准备交给容器管理的类UserBean
    public class UserBean {
    
        private Integer age;
    
        private String name;
    
        private List<String> phone;
    }

     

  2. 建立一个spring.xml放在resource目录下(固然你的项目必须是一个maven项目)
    <?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="user" class="com.example.demo.spring.UserBean"></bean>
    </beans>

     

  3. 启动容器并从容器中获取bean实例
    public class SpringStater {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
            UserBean userBean = context.getBean(UserBean.class);
        }
    }

    这样能够从容器中获取到UserBean的实例,而无需咱们写实例化代码。maven

相关文章
相关标签/搜索