Spring——创建对象、配置及依赖注入

4.IOC创建对象的方式

  1. 使用无参构造创建对象,默认!

  2. 假设我们要使用有参构造创建对象

    1. 下标赋值

      <bean id="user" class="net.cqwu.pojo.User">
                  <constructor-arg index="0" value="feliks"/>
              </bean>
      
      1. 类型赋值:不建议使用
          <bean id="user" class="net.cqwu.pojo.User">
              <constructor-arg type="java.lang.String" value="feliks2"/>
          </bean>
      
      1. 参数名
          <bean id="user" class="net.cqwu.pojo.User">
              <constructor-arg name="name" value="feliks3"/>
          </bean>
      

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了

User

public class User {
    private String name;

    //没有无参构造,报错
    public User(String name){
        this.name = name;
    }
//省略getter,setter
    public void show(){
        System.out.println("name:"+name);
    }
}

applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    1.下标赋值-->
<!--        <bean id="user" class="net.cqwu.pojo.User">-->
<!--            <constructor-arg index="0" value="feliks"/>-->
<!--        </bean>-->

<!--    2.类型赋值法:不建议使用-->
<!--    <bean id="user" class="net.cqwu.pojo.User">-->
<!--        <constructor-arg type="java.lang.String" value="feliks2"/>-->
<!--    </bean>-->

<!--3.直接通过参数名来创建-->
    <bean id="user" class="net.cqwu.pojo.User">
        <constructor-arg name="name" value="feliks3"/>
    </bean>

    <bean id="userT" class="net.cqwu.pojo.UserT"></bean>
</beans>

测试MyTest

import net.cqwu.pojo.User;
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("applicationContext.xml");

        User user = (User) context.getBean("user");
        User user2 = (User) context.getBean("user");
        user.show();
        System.out.println(user == user2);
    }
}

5.Spring配置

别名

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

Bean的配置

<!--
    id: bean 的唯一标识符,相当于对象名
    class: bean 对象所对应的全限定名:包名 + 类名
    name: 别名
-->
    <bean id="userT" class="net.cqwu.pojo.UserT" name="user2">
        <property name="name" value="feliks"></property>
    </bean>
UserT user = (UserT) context.getBean("user2");
        user.show();

import

团队开发时,将多个配置文件导入合并为一个

<import resource="beans1.xml"></import>

DI依赖注入

构造器注入

<beans>
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg ref="beanTwo"/>
        <constructor-arg ref="beanThree"/>
    </bean>

    <bean id="beanTwo" class="x.y.ThingTwo"/>

    <bean id="beanThree" class="x.y.ThingThree"/>
</beans>

Set方式注入!!!

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

【环境搭建】

  1. 复杂类型
public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}
  1. 真实测试对象
public class Student {

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> game;
    private String wife;//空指针
    private Properties info;
}
//get  set  toString省略
  1. applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="address" class="net.cqwu.pojo.Address">
        <property name="address" value="Chongqing"></property>
    </bean>
    <bean id="student" class="net.cqwu.pojo.Student">
    <!--第一种:普通值注入 -->
    <property name="name" value="feliks"></property>

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

    <!--数组注入-->
        <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="11111111"/>
                <entry key="银行卡" value="22222222"/>
            </map>
        </property>

        <!--Set-->
        <property name="game">
            <set>
                <value>lol</value>
                <value>bob</value>
                <value>coc</value>
            </set>
        </property>

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

        <!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">4029</prop>
                <prop key="姓名">feliks</prop>
                <prop key="专业">软件</prop>
                <prop key="username">admin</prop>
                <prop key="password">123456</prop>
            </props>
        </property>

    </bean>
</beans>
  1. MyTest
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
}
/*
* Student{
name='feliks'
, address=Address{address='Chongqing'}
, books=[西游记, 红楼梦, 三国, 水浒]
, hobbys=[魔方, 唱歌, 听歌]
, card={身份证=11111111, 银行卡=22222222}
, game=[lol, bob, coc]
, wife='null'
, info={学号=4029, password=123456, 专业=软件, 姓名=feliks, username=admin}
}
* */

拓展方式注入

详细解释见官方文档中的

XML Shortcut with the p-namespace
XML Shortcut with the c-namespace

对象

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


    //加上无参 和 有参构造器,才能使用c命名注入
    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}//省略getter setter toString

测试类

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

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

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

        <!--c命名空间注入,通过构造器注入:constructs-args-->
        <bean id="user2" class="net.cqwu.pojo.User" c:age="21" c:name="Feliks"/>
</beans>

注意:p 和 c命名空间注入不能直接使用,需要导入xml约束

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

Bean的作用域

官方文档:

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
  1. 单例模式(Spring默认机制)
<bean id="user2" class="net.cqwu.pojo.User" c:age="21" c:name="Feliks" scope="singleton"/>

测试

        User user = context.getBean("user2",User.class);
        User user2 = context.getBean("user2",User.class);
        System.out.println(user==user2);//true
  1. 原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="user2" class="net.cqwu.pojo.User" c:age="21" c:name="Feliks" scope="prototype"/>

测试

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

request session application只能在web开发中使用到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值