hooyantsing's Blog

第109次课程_Spring_IOC原理

字数统计: 1.8k阅读时长: 10 min
2020/02/19

源辰76班

第109次课程

2020.02.19

内容

Spring_IOC原理

项目路径:

1.XML方式

IOC01.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?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
          https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 1 -->
    <bean id="myUser"  class="com.yc.spring.bbs.bean.User">
        <property name="uname" value="武松"></property>
        <property name="upass"  value="abc123"></property>   
        <property name="head"  value="20.gif"></property>   
        <property name="gender"  value="1"></property>       
    </bean>
    
    <!-- 2 -->
    <bean primary="true"  class="com.yc.spring.bbs.bean.User">
        <property name="uname" value="石秀"></property>
        <property name="upass"  value="XYZ890"></property>   
        <property name="head"  value="345.gif"></property>   
        <property name="gender"  value="0"></property>       
    </bean>
    
    <!-- 3 -->
    <bean id="page1"  class="com.yc.spring.bbs.bean.Page">
        <property name="total"  value="100"></property>
        <property name="rows">
           <list>
               <value>湖南</value>   
               <value>广东</value>
               <value></value>       
               <value  type="java.lang.Integer">100</value>
           </list>
        </property>   
    </bean>
    
    <!-- 4 -->
    <bean id="board" primary="true"  class="com.yc.spring.bbs.bean.Board">
        <constructor-arg name="boardid"  value="100"></constructor-arg>
        <constructor-arg name="parentid"  value="200"></constructor-arg>
        <constructor-arg name="boardname"  value="jsp"></constructor-arg>
        <property name="parent"  ref="boardparent"></property>
        <property name="topicList">
           <list>
               <null/>
               <null/>
               <null/>
               <bean  class="com.yc.spring.bbs.bean.Topic">
                   <property name="uid"  value="400"></property>
               </bean>
               <null/>
           </list>
        </property>
    </bean>
    <bean id="boardparent" scope="prototype"  class="com.yc.spring.bbs.bean.Board">
        <constructor-arg name="boardid"  value="300"></constructor-arg>
        <constructor-arg name="parentid"  value="0"></constructor-arg>
        <constructor-arg name="boardname"  value="java"></constructor-arg>
    </bean>
    
    <!-- 5 -->
    <bean id="page2"  class="com.yc.spring.bbs.bean.Page">
        <property name="total"  value="200"></property>
        <property name="rows">
           <list>
               <bean  class="com.yc.spring.bbs.bean.User">
                   <property name="uname"  value="华荣"></property>
               </bean>
               <map>
                   <entry key="0734"  value="衡阳"></entry>
                   <entry key="0731"  value="长沙"></entry>
               </map>
               <set>
                   <value  type="java.lang.Integer">100</value>
                   <value>呵呵</value>
                   <ref bean="myUser"></ref>
               </set>
           </list>
        </property>
    </bean>
</beans>

E01locForXmlTest.java

测试文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.yc.spring.test.ioc;

import java.util.Map;
import java.util.Set;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yc.spring.bbs.bean.Board;
import com.yc.spring.bbs.bean.Page;
import com.yc.spring.bbs.bean.User;

/**
* 配置Spring,让测试方法全部测试通过
*/
public class E01IocForXmlTest {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("IOC01.xml");

    @Test
    public void test1() {
        User user = (User) context.getBean("myUser");
        Assert.assertNotNull(user);
        Assert.assertEquals("武松", user.getUname());
        Assert.assertEquals("abc123", user.getUpass());
        Assert.assertEquals("20.gif", user.getHead());
        Assert.assertEquals(Integer.valueOf(1), user.getGender());
    }

    // 必须设置主bean primary=true
    @Test
    public void test2() {
        User user = (User) context.getBean(User.class);
        Assert.assertNotNull(user);
        Assert.assertEquals("石秀", user.getUname());
        Assert.assertEquals("XYZ890", user.getUpass());
        Assert.assertEquals("345.gif", user.getHead());
        Assert.assertEquals(Integer.valueOf(0), user.getGender());
    }

    @Test
    public void test3() {
        Page page = (Page) context.getBean("page1");
        Assert.assertNotNull(page);
        Assert.assertEquals(100, page.getTotal());
        Assert.assertNotNull(page.getRows());
        Assert.assertEquals("湖南", page.getRows().get(0));
        Assert.assertEquals("广东", page.getRows().get(1));
        Assert.assertEquals(100, page.getRows().get(3));
    }

    @Test
    public void test4() {
        Board board = (Board) context.getBean("board");
        Assert.assertEquals((Integer) 100, board.getBoardid());
        Assert.assertEquals((Integer) 200, board.getParentid());
        Assert.assertEquals("jsp", board.getBoardname());
        
        
        Assert.assertEquals((Integer) 300, board.getParent().getBoardid());
        Assert.assertEquals("java", board.getParent().getBoardname());
        
        
        Assert.assertEquals(5, board.getTopicList().size());
        Assert.assertEquals(null, board.getTopicList().get(0));
        Assert.assertNull(board.getTopicList().get(1));
        Assert.assertEquals((Integer) 400, board.getTopicList().get(3).getUid());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void test5() {
        Page page = (Page) context.getBean("page2");
        Assert.assertNotNull(page);
        Assert.assertEquals(200, page.getTotal());
        Assert.assertNotNull(page.getRows());

        /**
         * 测试实体对象
         */
        User user = (User) page.getRows().get(0);
        Assert.assertEquals("华荣", user.getUname());
        /**
         * 测试Map集合
         */
        Map<String, Object> map = (Map<String, Object>) page.getRows().get(1);
        Assert.assertEquals("衡阳", map.get("0734"));
        Assert.assertEquals("长沙", map.get("0731"));
        /**
         * 测试Set集合
         */
        User wuSong = (User) context.getBean("myUser");
        Set<Object> set = (Set<Object>) page.getRows().get(2);
        Assert.assertEquals(true, set.contains(100));
        Assert.assertEquals(true, set.contains(wuSong));
        Assert.assertEquals(true, set.contains("呵呵"));
    }
}

2.注解方式

BeanConfig.java

相当于XML配置文件

自动装配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.yc.spring;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

import com.yc.spring.bank.bean.Account;
import com.yc.spring.bank.biz.impl.AccountBizImpl;
import com.yc.spring.bbs.bean.User;

/**
* 注解配置bean 类
*/
    
    /*
     * 自动装配
     * 1.组件注解:Component 注解,加在类上,相当于Bean
     *     (如果说Configuration注解的类内部为本地居民Bean,那么Component注解标记为属于本地居民却在外地的Bean)
     *         Component    通用 组件
     *         Service        biz类
     *         Repository    dao类
     *         Controller    控制器
     * 2.属性上面加上@Autowired注解,可以让spring容器自动的注入一个对象,实现自动装配
     * 3.在配置类加上@ComponentScan,是对某个包下的所有类进行扫描,扫描到加了"1.组件注解"的bean,自动添加到IOC中并完成装载
     *
     */

@Configuration   // ->  <beans>
@ComponentScan("com.yc.spring")  // 配置spring扫描的包路径
public class BeanConfig {
    
    /*
     * @Bean(#name)        == <bean id="#name"></bean>         //设置实体类名
     * @Primary            == <bean primary="ture"></bean>     //.Class唯一
     * @Scope("prototype") == <bean scope="prototype"></bean>//单例,调用一次创建一个新对象
     *            prototype   -> ConfigurableBeanFactory.SCOPE_PROTOTYPE
     */
    
    /**
     * 创建 Account 对象的方法
     * @return
     */
    @Bean("accountBiz")
    public AccountBizImpl createAcountBiz() {
        return new AccountBizImpl();
    }
    
    @Bean("account")
    @Primary
    public Account createAcount() {
        return new Account();
    }
    
    @Bean("account1")
    @Scope("prototype")
    public Account createAcount1() {
        return new Account();
    }
    
    @Bean("account2")
    public Account createAcount2() {
        // 必须与 createAcount3 方法一样
        // 单例模式
        return Account.getInstance();
    }
    
    @Bean("account3")
    public Account createAcount3() {
        // 必须与 createAcount2 方法一样
        // 单例模式
        return Account.getInstance();
    }
    
    int count;
    @Bean("account4")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Account create1() {
        return count++ < 3 ? new Account() : Account.getInstance();
    }
    
    @Bean("myUser")
    public User createUser() {
        User user = new User();
        /**
         * 使用java代码设置属性
         */
        user.setUname("武松");
        user.setUpass("abc123");
        user.setHead("20.gif");
        user.setGender(1);
        return user;
    }
}

UserBiz.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.yc.spring.taobao;
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.stereotype.Service;
/*
* 业务类
* @Component => @Bean
*/
@Service
public class UserBiz {
    @Autowired
    private UserDao udao;
    public UserDao getUdao() {
       return udao;
    }
    public void setUdao(UserDao udao) {
       this.udao = udao;
    }
}

UserDao.java

1
2
3
4
5
6
package com.yc.spring.taobao;
import  org.springframework.stereotype.Repository;
@Repository
public class UserDao {
    
}

E03locForAnnoTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Class<?> beanConfigClass;
{
       try {
           beanConfigClass =  Class.forName("com.yc.spring.BeanConfig");
           //相当于:beanConfigClass =  BeanConfig.class;
       } catch (ClassNotFoundException e) {
           throw new RuntimeException("请定义注解配置类 (BeanConfig) !!!!",e);
       }
}
             // 创建注解容器上下文对象
          ApplicationContext cxt = new AnnotationConfigApplicationContext(beanConfigClass);
//相当于:ApplicationContext cxt = new AnnotationConfigApplicationContext(BeanConfig.class);
    
    //=====================================================================//
    @Test
    public void testUserBiz() {
       com.yc.spring.taobao.UserBiz ubiz =  cxt.getBean(com.yc.spring.taobao.UserBiz.class);
       
       Assert.assertNotNull(ubiz);
       
       Assert.assertNotNull(ubiz.getUdao());
    }
CATALOG