Spring框架基础学习(二)

创建一个spring项目

上一篇文章中介绍了IOC控制反转及DI依赖注入的思想,在之前的项目开发中new一个对象是我们自己做的,如果使用Spring框架的话,创建对象这份工作由我们自己执行反转给spring帮我们执行.Spring是一个容器,他将帮我们管理对象

这里使用Myeclipse创建一个简单的spring项目.
步骤1:新建一个web项目
步骤2:右击src-->Myeclipse-->add Spring Capabilities

image.png

步骤3:选择要引入的jar包,next-->finsh
image.png

这样就完成了,向web项目中引入spring所需jar包,并创建了applicationContext.xml配置文件
也可自行去spring官网下载jar包,进行导入
https://repo.spring.io/release/org/springframework/spring/

将自定义对象由自己创建移交给spring创建

1.首先先创建两个类User和Pet,使用javabean创建原则


public class User {
    private int uid;
    private String username;
    private String password;
    
    //加入宠物字段
    private Pet upet;
    
    
    public User(String username, Pet upet) {
        System.out.println("String, pet");
        this.username = username;
        this.upet = upet;
    }
    public User(Integer username, Pet upet) {
        System.out.println("方法二:int, pet");
        this.username = username.toString();
        this.upet = upet;
    }
    public User(Pet upet,Integer username) {
        System.out.println("方法三:int, pet");
        this.username = username.toString();
        this.upet = upet;
    }
    public Pet getUpet() {
        return upet;
    }
    public void setUpet(Pet upet) {
        this.upet = upet;
    }
    public User(){
        System.out.println("User 对象空参构造");
    }
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    
    @Override
    public String toString() {
        return "User [uid=" + uid + ", username=" + username + ", password="
                + password + ", upet=" + upet + "]";
    }
    public void userInit(){
        System.out.println("user init");
    }
    
    public void userDestory(){
        System.out.println("user destory");
    }
    

}

Pet类

package bean;

public class Pet {
    private String petType;
    private String color;
    public String getPetType() {
        return petType;
    }
    public void setPetType(String petType) {
        this.petType = petType;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    @Override
    public String toString() {
        return "Pet [petType=" + petType + ", color=" + color + "]";
    }
    

}

2.在applicationContext.xml中配置bean

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- name是起一个名字,我们可以通过这个name来利用容器获取对象 
    name可以使用特殊字符.可重复(但一般不重复) -->
<!-- id与name作用基本相同,但不推荐使用,不能支持特殊字符不能重复  -->
<!-- class是被管理对象的全报名,spring会通过这个包来创建对象  -->
<!-- request在web环境下,如果scope属性为request那么这个对象被创建出来,他的生命周期会与request请求一致  -->
<bean name="user" class="bean.User" lazy-init="true" scope="singleton" init-method="userInit" destroy-method="userDestory">
    <property name="uid" value="2"></property>
</bean>

</beans>

3.使用一个测试类进行测试

package test;

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

import bean.User;

public class HelloSpring {
    //在之前项目开发中new对象使我们自己做的
    @Test
    public void Test1(){
        User u = new User();
        u.setUid(1);
        System.out.println(u);
    }
    //IOC的反转:创建对象这份工作由我们自己执行反转给spring帮我们执行;
    //IOC的控制:就是由Spring帮我们负责创建销毁对象,掌控对象的生命周期等,我们在需要使用对象的是有跟Spring申请即可;
    //IOC是一种编程思想,也是一种新的设计模式.他需要DI(依赖注入)的支持
    //Spring是一个容器,他将帮我们管理对象
    @Test
    public void Test2(){
        //根据spring配置文件获取容器对象
        //ApplicationContext配置的所有bean都会子啊容器创建的时候被创建出来
        //如果配置的bean较多,那么创建容器的时候,会产生内存过大的问题,这种情况在机械性能比较落后的时候比较明显
        //延迟加载lazy-init为true就是创建容器时不加载配置的bean对象,在获取的时候才创建;
        //scope="singleton"默认值是 单例的只创建一个对象  "prototype"多力例,在获取的时候创建新的对象,但在特殊情况下需要使用多例的
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        //User u=(User)ac.getBean("user");//法一
        //通过getBean获取配置好的user对象(程序员向spring容器要对象)
        User u=ac.getBean(User.class);//法二 通过User字节码对象获得
        System.out.println(u);
    }
     @Test
     public void Test3(){
        
        //scope="singleton"默认值是 单例的只创建一个对象  "prototype"多力例,在获取的时候创建新的对象,但在特殊情况下需要使用多例的
         ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        User u1=ac.getBean(User.class);//法二 通过User字节码对象获得
        User u2=ac.getBean(User.class);
        User u3=ac.getBean(User.class);
        System.out.println(u1==u2);
        //关闭容器对象,就会触发bean的destorymethod(单例时才能销毁)
        ac.close();
     }
}

通过使用Junit Test 测试Test2方法可得到以下执行结果


image.png

可见spring帮我们创建了对象,并注入了初始值

属性注入

属性注入分为三种形式
1.set注入
这要求要实现注入的类,设置set()方法
applicationContext.xml配置如下

<bean name="user" class="bean.User" lazy-init="true" scope="singleton" init-method="userInit" destroy-method="userDestory">
    <property name="uid" value="2"></property>
    <property name="username" value="小明"></property>
    <property name="password" value="123456"></property>
    <!--引用类型的注入  -->
    <property name="upet" ref="dog"></property>
</bean>

<!-- 将pet对象交给spring容器管理 -->
<bean name="dog" class="bean.Pet">
    <property name="petType" value="二哈"></property>
    <property name="color" value="红色"></property>

</bean>

<property/>进行属性配置,ref可实现引用

2.构造方法注入
要求被注入属性的类,实现有参构造方法

<!--构造方法注入  -->
<bean name="user1" class="bean.User">
<!--name调用构造方法的参数名称 value是注入值类型 ref注入引用类型  -->
<!-- type 是指定 参数的类型 -->
<!-- index 指定参数位置 -->
    <constructor-arg name="username" value="55" type="java.lang.Integer" index="0"></constructor-arg>
    <constructor-arg name="upet" ref="dog" index="1"></constructor-arg>
    
</bean>

3.复杂属性注入
这里是指对数组,list,set,map,properties类型的属性注入
新建一个包含上述类型的类

package bean;

import java.util.*;

public class MyCollection {

    //数组
    private Object[] array;
    //list
    private List list;
    //set
    private Set set;
    //map
    private Map map;
    //properties
    private Properties prop;
    public Object[] getArray() {
        return array;
    }
    public void setArray(Object[] array) {
        this.array = array;
    }
    public List getList() {
        return list;
    }
    public void setList(List list) {
        this.list = list;
    }
    public Set getSet() {
        return set;
    }
    public void setSet(Set set) {
        this.set = set;
    }
    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = map;
    }
    public Properties getProp() {
        return prop;
    }
    public void setProp(Properties prop) {
        this.prop = prop;
    }
    @Override
    public String toString() {
        return "MyCollection [array=" + Arrays.toString(array) + ", list="
                + list + ", set=" + set + ", map=" + map + ", prop=" + prop
                + "]";
    }
}

applicationContext.xml配置属性

<bean name="collection" class="bean.MyCollection">
    <!--array  -->
    <property name="array">
        <array>
            <value>123</value>
            <value>abc</value>
            <ref bean="dog"/>
        </array>
    </property>
    
    <!--list  -->
    <property name="list">  
        <list>
            <value>456</value>
            <value>vcvc</value>
            <ref bean="user1"/>
        </list>
    </property>
    
    <!--set  -->
    <property name="set">   
        <set>
            <value>798</value>
            <value>aaa</value>
            <ref bean="user1"/>
        </set >
    </property>
    
    <!--map  -->
    <property name="map">
        <map>
        <entry key="username" value="root"></entry>
        <entry key="password" value="123456"></entry>
        <entry key-ref="user1" value-ref="dog"></entry>

        </map>
    </property>
    
    <!--properties  -->
    <property name="prpo">
        <props>
        <prop key="name">小花</prop>
        <prop key="age">23</prop>
        </props>
    </property>
</bean>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容