J2EE进阶学习——Spring框架(二):IOC

一、IOC入门

第一步:导入jar包

  • 做Spring最基本功能的时候,导入四个核心jar包即可
  • 导入支持日志输出的jar包
只需导入选中包即可完成基本操作

第二步:创建类,在类里面创建方法

IOC底层原理

原始做法

package com.TiHom.ioc;

/**
 * @author TiHom
 */
public class User {
    public void add(){
        System.out.println("add...");
    }

    public static void main(String[] args) {
        //原始做法
        User user = new User();
        user.add();
    }
}

第三步:创建Spring配置文件,配置创建类

1.Spring核心配置文件名称和位置不是固定的

  • 建议放到src下面,官方建议applicationContext.xml

2.编写xml文件时,需要引入schema约束,参考Spring文档中的写法,下面是Spring Framework文档的网站

https://docs.spring.io/spring/docs/current/spring-framework-reference/

<?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="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

可以看到在文档中xml文件是这样来配置的

3.配置对象创建

<!-- ioc入门 -->
    <bean id="user" class="com.TiHom.ioc.User"></bean>

4.写代码测试对象创建

  • 这段代码在测试中使用,实际开发不用写
package com.TiHom.ioc;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author TiHom
 */
public class TestIOC {
    @Test
    public void testUser(){
        //1.加载spring的配置文件,根据创建对象
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2.得到配置创建的对象
        User user = (User) context.getBean("user");
        System.out.println(user);
        user.add();
    }
}



二、bean实例化的三种方式(后面两种基本不用,但要求知道)

1.使用类的无参构造创建对象(重点)

在User类中
public User(){}
在xml文件中
<bean id="user" class="com.TiHom.ioc.User" ></bean>

2.静态工厂创建对象

静态工厂方法

pubic class Bean2Factory{
    //静态的方法,返回Bean2对象
    public static Bean2 getBean2(){
        return new Bean2();
    }   
}

xml中的配置

<bean id="bean2" class="com.TiHom.bean.Bean2Factory" factory-method="getBean2"></bean>

3.实例工厂创建对象

实例工厂方法

public class Bean3Factory{
    //普通的方法,返回Bean3对象
    public Bean3 getBean3(){
        return new Bean3();
    }
}

xml中的配置

<!-- 先创建工厂对象 -->
<bean id="bean3Factory" class="com.TiHom.bean.Bean3Factory" ></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean> 

Bean3

public class Bean3{
    public void add(){
        .....
    }
}


三、bean标签常用属性

  1. id属性:根据id值得到配置对象
  2. class属性:创建对象所在类的全路径
  3. name属性:功能和id属性一样的,id属性值中不能包含特殊符号,但是name可以(不怎么用,这是遗留性的)
  4. scope属性
  • singleton:默认值,单例
  • prototype:多例
<bean id="xxx" class="xxx" scope="prototype"></bean>

User user1 =  (User) context.getBean("xxx");
User user2 =  (User) context.getBean("xxx");

输出的结果就是两个user为不同的地址


四、属性注入

1.创建对象的时候,向类里面属性里面设置值
2.属性注入的方式:(java代码中)


三种注入方式

3.在Spring框架里面,支持前两种方式

  • set方法注入(重点,实际开发用的最多)
    创建一个Book对象
public class Book{
    private String bookname;
    public void setBookname(String bookname){
        this.bookname = bookname;
    }
    
    public void demobook(){
        .....
    }
}

xml中的配置

<bean id="book" class="com.TiHom.property.Book">
    <!-- 
          name属性值:类里面定义的属性名称
          value属性值:设置具体的值
    -->
    <property name="bookname" value="龙族"></property>
</bean>

  • 有参构造注入
    xml中配置
<bean id="demo" class="com.TiHom.property.PropertyDemo1">
    <!-- 有参注入 -->
    <constructor-arg name="username" value="TiHom"></constructor-arg>
</bean>

PropertyDemo1

public class PropertyDemo1{
    private String username;
    public PropertyDemo1(String username){
        this.username = username;
    }
    public void test(){
        .....
    }
}


五、注入对象属性值

创建一个UserDao

public class UserDao {
    public void add(){
        System.out.println("add....");
    }
}

创建一个UserService

public class UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add(){
        System.out.println("service...");
        userDao.add();
    }
}

xml

<bean id="userDao" class="com.TiHom.ioc.UserDao"></bean>
    <bean id="userService" class="com.TiHom.ioc.UserService">
        <!--
            name属性:service类里面属性的名称
            ref属性:dao配置bean标签id值
        -->
        <property name="userDao" ref="userDao"></property>
    </bean>
xml配置

p名称空间注入

<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"
        xmlns:p="http://www.springframework.org/schema/p">
<bean id="person" class="com.TiHom.property.Person" p:pname="xxx"></bean>


六、复杂类型注入

1.数组
2.list集合
3.map集合
4.properties类型

xml

<bean id="person" class="com.TiHom.ioc.Person">
        <!-- 数组 -->
        <property name="arrs">
            <list>
                <value></value>
                <value></value>
                <value></value>
            </list>
        </property>
        <!-- list -->
        <property name="list">
            <list>
                <value></value>
            </list>
        </property>
        <!-- map -->
        <property name="map">
            <map>
                <entry key="aaa" value="xx"></entry>
            </map>
        </property>
        <!-- properties -->
        <property name="properties">
            <props>
                <prop key="driverClass">com.mysql.jdbc.Driver</prop>
                <prop key="username">root</prop>
            </props>
        </property>
    </bean>

Person

public class Person {
    private String pname;

    private String[] arrs;
    private List<String> list;
    private Map<String,String> map;
    private Properties properties;

    public void setPname(String pname) {
        this.pname = pname;
    }

    public void setArrs(String[] arrs) {
        this.arrs = arrs;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void test1(){
        System.out.println(arrs);
        System.out.println(list);
        System.out.println(map);
        System.out.println(properties);
    }
}


七、IOC和DI的区别

1.IOC:控制反转,将对象的创建交给Spring进行配置
2.DI:依赖注入,将类里面的属性中设置值
3.关系:依赖注入不能单独存在,需要在IOC的基础上完成操作

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容