什么是IOC:通过配置创建对象,管理对象的依赖关系

配置文件的管理

1.创建配置文件

图片说明

2.spring Bean 管理

创建Bean的方式:

图片说明

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 创建bean方式:第一种XML -->
    <bean id="user" class="com.testfan.ioc.User">
       <constructor-arg name="name" value="hello"></constructor-arg>
       <constructor-arg name="sex" value="男"></constructor-arg>
        <property name="age" value="20"></property>
        <property name="car" ref="cartest"></property>
        <property name="carList">
            <list>
                <bean class="com.testfan.ioc.Car">
                    <property name="name" value="奔驰"></property>
                    <property name="price" value="20000"></property>
                </bean>
                <ref bean="cartest" />
                <ref bean="cartest" />
            </list>
        </property>
        <property name="carSet">
        <set>
        <bean class="com.testfan.ioc.Car">
                    <property name="name" value="奔驰"></property>
                    <property name="price" value="20000"></property>
                </bean>
                <ref bean="cartest" />
                <ref bean="cartest" />
        </set>
        </property>
    </bean>

    <!-- 创建bean方式:第二种,包扫描 注解方式 -->
    <!-- 默认情况下,<context:component-scan>查找使用构造型(stereotype)注解所标注的类,如@Component(组件),@Service(服务),@Controller(控制器),@Repository(数据仓库) -->
    <context:component-scan
        base-package="com.testfan.ioc" />
        <!-- 集成配置文件:路径与spring配置文件同级目录 -->
    <context:property-placeholder
        location="classpath*:test.properties" />
</beans>

第一种方式:基于xml配置Bean

第二种方式:包扫描(使用注解定义对象类)
图片说明
1.注解类型:基于对象类
@Component("userDao"):使用@Component注解在UserDao类声明处对类进行标注,它可以被Spring容器识别,Spring容器自动将POJO转换为容器管理的Bean(类似于xml文件中定义Bean
@Repository:用于对DAO实现类进行标注;
@Service:用于对Service实现类进行标注;
@Controller:用于对Controller实现类进行标注;
@scope("")设置对象的生命周期
2.注解类型:基于对象属性
@Value("${name}") :从配置文件中集成的配置文件 中取值
@AutoWired:自动注入(在对象的属性中注入一个 spring中已定义的其他对象)
@AutoWired(required-false):启动时 不检查该注解
@Autowired(required=false) //自动注入 required=false 启动时候不检查
private User user; //User:为spring 已定义的bean名称
默认通过byType查找对象
@Resource
默认通过byType查找对象
@Resource(name="name1")
通过byName=name1查找对象

3.使用配置文件

         ApplicationContext context = new ClassPathXmlApplicationContext("ioc_test.xml");
        User user = (User) context.getBean("user");

        User user2 = (User) context.getBean("user");
        System.out.println(user2==user); //false