1.2.spring ioc

控制反转 ioc

一种设计思路

把创建对象的主动权由 程序 交到 程序员 手中

 

依赖注入 DI

是 ioc 的具体实现

 

简单实现

1.maven

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
</dependency>

2.实体类 

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bean {
    private String name;
    private LessBean lessBean;
    private String[] arr;
    private List<String> list;
    private Map<String,String> map;
    private Set<String> set;

}
@Data
@AllArgsConstructor
public class LessBean {
    private String name;
}

  

  

3.配置类

<?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="bean" class="ioc.Bean">
            <property name="name" value="ljk"></property>
            <property name="lessBean" ref="lessbean"></property>
            <property name="arr">
                <array>
                    <value>arr1</value>
                    <value>arr2</value>
                </array>
            </property>
            <property name="list">
                <list>
                    <value>list1</value>
                </list>
            </property>
            <property name="map">
                <map>
                    <entry key="1" value="map1"></entry>
                </map>
            </property>
            <property name="set">
                <set>
                    <value>set1</value>
                </set>
            </property>
        </bean>
        <bean id="lessbean" class="ioc.LessBean">
            <constructor-arg name="name" value="ljw"></constructor-arg>
        </bean>
</beans>

  

4.测试

@Test
    public void iocTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("myx.xml");
        Bean bean = context.getBean("bean", Bean.class);
        System.out.println(bean);

    }

  

posted @ 2021-02-26 00:39  ljk12345  阅读(42)  评论(0)    收藏  举报