【Spring】HelloSpring,IOC创建对象的方式,Spring配置,依赖注入

1.HelloSpring

1.1使用过程

1.导入jar包

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

2.编写一个java类

public class Hello {
   private String name;

   public String getName() {
       return name;
  }
   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("Hello,"+ name );
  }
}

3.编写spring配置文件 , 这里我们命名为beans.xml

<?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">
<!--    使用Spring来创建对象,在Spring这些都称为Bean
    类型 变量名  =  new 类型();
    Hello hello = new Hello();
    bean = 对象 new Hello();

    id = 变量名
    class = new 的对象;
    property 相当于给对象中的属性设置一个值!
-->
    <bean id="hello" class="com.adie.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>

</beans>

4.进行测试

import com.adie.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象!
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring中管理,我们要使用,直接去里面取出来就可以!
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

根据以上内容,我们一定要弄清楚几个问题

  • Hello 对象是谁创建的 ? hello 对象是由Spring创建的
  • Hello 对象的属性是怎么设置的 ? hello 对象的属性是由Spring容器设置的

这个过程就叫控制反转(IOC) :

  • 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
  • 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .

依赖注入 : 就是利用set方法来进行注入的.(在上述案例中,如果我们在Hello的java类中删除set方法,在beans.xml中将会报错)

IOC是一种编程思想,由主动的编程变成被动的接收

可以通过ClassPathXmlApplicationContext类去浏览一下底层源码 。

1.2修改案例一

在上一个博客中的案例,新增一个Spring配置文件beans.xml

<?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="mysqlImpl" class="com.adie.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.adie.dao.UserDaoOracleImpl"/>

    <bean id="UserServiceImpl" class="com.adie.service.UserServiceImpl">
<!--
ref:引用Spring容器中创建好的对象
value:具体的值,基本数据类型
-->
        <property name="userDao" ref="mysqlImpl"/>
    </bean>

</beans>

测试

@Test
public void test2(){
   //获取ApplicationContext;拿到Spring的容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //容器在手,需要什么就直接get什么
        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
        userServiceImpl.getUser();
}

到了现在 , 我们彻底不用再程序中去改动了 , 要实现不同的操作 , 只需要在xml配置文件中进行修改 , 所谓的IoC,就是 对象由Spring 来创建 , 管理 , 装配 !

2.IOC创建对象的方式

2.1使用无参构造创建对象,默认

1、User.java

package com.adie.pojo;
public class User {
    private String name;

    public User(String name){
        this.name=name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void show(){
        System.out.println("name="+name);
    }
}

2、beans.xml

<?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.kuang.pojo.User">
       <property name="name" value="adie"/>
   </bean>

</beans>

3、测试类

@Test
public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //在执行getBean的时候, user已经创建好了 , 通过无参构造
   User user = (User) context.getBean("user");
   //调用对象的方法 .
   user.show();
}

结果发现,在调用show方法之前,User对象已经通过无参构造初始化了!
在这里插入图片描述

2.2通过有参构造创建对象

​ 1.下标赋值

<bean id="user" class="com.adie.pojo.User">
    <constructor-arg index="0" value="a碟碟"/>
</bean>

​ 2.通过类型创建,不建议使用

<bean id="user" class="com.adie.pojo.User">
    <constructor-arg type="java.lang.String" value="adie"/>
</bean>

​ 3.直接通过参数名来设置

<bean id="user" class="com.adie.pojo.User">
    <constructor-arg name="name" value="adie1"/>
</bean>

2.3拓展案例

1、创建一个UserT . java

package com.adie.pojo;

public class UserT {
    private String name;

    public UserT(){
        System.out.println("UserT被创建了");
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void show(){
        System.out.println("name="+name);
    }
}

2.beans.xml

<?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.adie.pojo.User">
        <property name="name" value="adie"/>
    </bean>


    <bean id="userT" class="com.adie.pojo.UserT">
    </bean>
    
</beans>

3、测试类和上面一个案例一致

@Test
public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //在执行getBean的时候, user已经创建好了 , 通过无参构造
   User user = (User) context.getBean("user");
   //调用对象的方法 .
   user.show();
}

注意到这里我们并没有使用userT,查看一下结果
在这里插入图片描述

无论用不用在xml里面写的对象都创建了,Spring在创建bean的时候就帮我们实例化了

更改一下测试类

import com.adie.pojo.User;
import com.adie.pojo.UserT;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        User user2=(User)context.getBean("user");
        System.out.println(user==user2);
    }
}

在这里插入图片描述

说明内存中只有一份实例。

结论:在配置文件加载的时候。其中管理的对象都已经初始化了!

3.Spring配置

3.1别名

<!--    别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="adie"/>

3.2Bean的配置

<!--
id:bean 的唯一标识符,也就是我们学的对象名
class:bean 对象所对应的全限定名:包名+类型
name:也是别名,而且name可以同时取多个别名,别名之间可以用逗号分隔,也可以用空格分隔
-->
<bean id="userT" class="com.adie.pojo.UserT" name="u5 u4,u3">
    <property name="name" value="a碟2"/>
</bean>

3.3import

团队的合作通过import来实现

可以将多个配置文件,导入合并为一个

假设现在项目有很多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的

<!--    导入的.xml中创建的同种对象,属性同名不同值,下面的值会覆盖掉上面的-->
    <import resource="beans3.xml"/>
    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>

4.依赖注入

4.1构造器注入

前面已经说过了

4.2Set方式注入【重点】

  • 依赖注入:Set注入

    • 依赖:bean对象的创建依赖于容器!
    • 注入:bean对象中的所有属性,由容器来注入!

    【环境搭建】

    1.复杂类型

    package com.adie.pojo;
    
    public class Address {
        private String address;
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public String getAddress() {
            return address;
        }
    
        @Override
        public String toString() {
            return "Address{" +
                    "address='" + address + '\'' +
                    '}';
        }
    }
    
    

    2.真实测试对象

    package com.adie.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    
    import java.util.*;
    
    public class Student {
        private String name;
        private Address address;
        private  String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", address=" + address.toString() +
                    ", books=" + Arrays.toString(books) +
                    ", hobbys=" + hobbys +
                    ", card=" + card +
                    ", games=" + games +
                    ", wife='" + wife + '\'' +
                    ", info=" + info +
                    '}';
        }
    
        public void setBooks(String[] books) {
            this.books = books;
        }
    
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
    
        public void setCard(Map<String, String> card) {
            this.card = card;
        }
    
        public void setGames(Set<String> games) {
            this.games = games;
        }
    
        public void setWife(String wife) {
            this.wife = wife;
        }
    
        public void setInfo(Properties info) {
            this.info = info;
        }
    
        public String getName() {
            return name;
        }
    
        public Address getAddress() {
            return address;
        }
    
        public String[] getBooks() {
            return books;
        }
    
        public List<String> getHobbys() {
            return hobbys;
        }
    
        public Map<String, String> getCard() {
            return card;
        }
    
        public Set<String> getGames() {
            return games;
        }
    
        public String getWife() {
            return wife;
        }
    
        public Properties getInfo() {
            return info;
        }
    }
    

    3.beans.xml

    <?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="student" class="com.adie.pojo.Student">
    <!--        第一种,普通值注入,value-->
            <property name="name" value="a碟"/>
        </bean>
        
    </beans>
    

    4.测试类

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            Student student = (Student) context.getBean("student");
            System.out.println(student.getAddress());
        }
    }
    

注入方式:

1、常量注入

 <bean id="student" class="com.adie.pojo.Student">
<!--        第一种,普通值注入,value-->
        <property name="name" value="a碟"/>
 </bean>

2、Bean注入

注意点:这里的值是一个引用,ref

 <bean id="address" class="com.adie.pojo.Address">
     <property name="address" value="郴州"/>
 </bean>
 
 <bean id="student" class="com.adie.pojo.Student">
     <!--        第二种,Bean注入,ref-->
     <property name="address" ref="addr"/>
 </bean>

3、数组注入

 <bean id="student" class="com.adie.pojo.Student">
     <!--        数组注入-->
     <property name="books">
         <array>
             <value>西游记</value>
             <value>红楼梦</value>
             <value>水浒传</value>
         </array>
     </property>
 </bean>

4、List注入

 <bean id="student" class="com.adie.pojo.Student">
<!--        List注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>
</bean>

5、Map注入

 <bean id="student" class="com.adie.pojo.Student">
<!--        Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="123456789"/>
                <entry key="银行卡" value="222222222"/>
            </map>
        </property>
 </bean>

6、Set注入

 <bean id="student" class="com.adie.pojo.Student">
<!--        Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
 </bean>

7、null注入

 <bean id="student" class="com.adie.pojo.Student">
<!--        null-->
        <property name="wife">
            <null/>
        </property>
 </bean>

8、Properties注入

 <bean id="student" class="com.adie.pojo.Student">
<!--        Properties-->
        <property name="info">
            <props>
                <prop key="学号">201901020241</prop>
                <prop key="性别"></prop>
                <prop key="姓名">a碟</prop>
            </props>
        </property>
  </bean>

完整xml配置

<?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="address" class="com.adie.pojo.Address">
        <property name="address" value="郴州"/>
    </bean>


    <bean id="student" class="com.adie.pojo.Student">

<!--        第一种,普通值注入,value-->
        <property name="name" value="a碟"/>

<!--        第二种,Bean注入,ref-->
        <property name="address" ref="address"/>

<!--        数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>

<!--        List-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>

<!--        Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="123456789"/>
                <entry key="银行卡" value="222222222"/>
            </map>
        </property>

<!--        Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>

<!--        null-->
        <property name="wife">
            <null/>
        </property>

<!--        Properties-->
        <property name="info">
            <props>
                <prop key="学号">201901020241</prop>
                <prop key="性别"></prop>
                <prop key="姓名">a碟</prop>
            </props>
        </property>
    </bean>

</beans>

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
}

在这里插入图片描述

4.3拓展方式注入

p命名和c命名注入

User.java :

package com.adie.pojo;

public class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

1、P命名空间注入 : 需要在头文件中加入约束文件

导入约束 : xmlns:p=“http://www.springframework.org/schema/p”

<!--P(属性: properties)命名空间 , 属性依然要设置set方法,可以直接注入属性的值:property-->
<bean id="user" class="com.adie.pojo.User" p:name="哈哈" p:age="15"/>

2、c 命名空间注入 : 需要在头文件中加入约束文件

导入约束 : xmlns:c=“http://www.springframework.org/schema/c”

<!--    c命名空间注入,通过构造器注入:construct-args-->
<!--    prototype原型模式:每次从容器中get的时候,都会产生一个新对象-->
<bean id="user2" class="com.adie.pojo.User" c:age="18" c:name="a碟"/>

**注意:**在C命名空间中相当于通过构造器注入,所以我们一定需要具有有参构造器

完整xml配置

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.adie.pojo.User" p:name="哈哈" p:age="15"/>

<!--    c命名空间注入,通过构造器注入:construct-args-->
<!--    prototype原型模式:每次从容器中get的时候,都会产生一个新对象-->
    <bean id="user2" class="com.adie.pojo.User" c:age="18" c:name="a碟"/>

</beans>

4.4bean的作用域

在这里插入图片描述

主要掌握前两种:单例和原型

**1.Singleton **单例模式(设计模式中很经典的)(并发情况可能会产生延迟或者数据不一致)

Spring默认机制

在这里插入图片描述

<bean id="user2" class="com.adie.pojo.User" c:age="18" c:name="a碟" scope="singleton"/>

测试

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
    User user = context.getBean("user2", User.class);
    User user2 = context.getBean("user2", User.class);
    System.out.println(user==user2);
}

结果输出为true

2.Prototype 原型模式(有些浪费资源)

每次从容器中get的到时候,都会产生一个新对象!

在这里插入图片描述

<bean id="user2" class="com.adie.pojo.User" c:age="18" c:name="a碟" scope="prototype"/>

测试

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
    User user = context.getBean("user2", User.class);
    User user2 = context.getBean("user2", User.class);
    System.out.println(user==user2);
}

结果输出为false

3.其余的request,session,application。这些只能在web开发中使用到!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a碟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值