使用Spring框架入门一:基于XML配置的IOC/DI的使用

Posted 宋兴柱-Sindrol

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Spring框架入门一:基于XML配置的IOC/DI的使用相关的知识,希望对你有一定的参考价值。

 

一、Spring框架

  1、方法一:逐项导入基础依赖包:

    spring-core、spring-beans、spring-context、spring-expression

  2、方法二:最简洁的导入,直接导入spring-context包:  

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>

  在pom.xml中加入上spring-context的依赖,它便会自动导入上述四个包。

  3、参考本项目结构图:

  

 

二、操作案例

  1、建立几个类对象,便于测试。

  

package test1;

import lombok.Data;

@Data
public class User {

    private String name;
    private int age;

    public void add() {
        System.out.println("user add method executed.");
    }

}

  注意,此类中,使用了lombok框架的@Data方式来实现的Getter和Setter和无参构造函数。引入lombok的方法是添加下列依赖,并为Idea安装一个lombok的插件,并启动注释的编译:

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>provided</scope>
</dependency>

  2、建立一个非静态的工厂类,用于测试非静态工厂方式创建Bean。

package test1;

public class UserFactory {
    public User createUser() {
        User user = new User();
        user.setAge(12);
        user.setName("张三");
        return user;
    }
}

  3、再创建一个的工厂类,添加一个静态方法,用于测试静态方法创建Bean。

package test1;

public class UserStaticFactory {
    public static User createUser() {
        User user = new User();
        user.setAge(22);
        user.setName("张五");
        return user;
    }
}

  4、再建立一个Student类,用来测试多种不同构造函数的情况:

package test1;

import lombok.Data;

import java.util.List;
import java.util.Map;

@Data
public class Student {
    private final String name;
    private final int age;
    private List<User> users;
    private User user;
    private Map<String, String> map;

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

    public Student(User user) {
        this.user = user;
        this.name = "另外一个有参数构建Name1";
        this.age = 2;
    }

    public Student(List<User> users) {
        this.users = users;
        this.name = "另外一个有参数构建Name2";
        this.age = 33;
    }

    public Student(Map<String, String> map) {
        this.map = map;
        this.name = "另外一个有参数构建Name2";
        this.age = 33;
    }
}

 

  5、在Maven项目的resources中添加一个xml(在WEB项目中要放在/WEB-INF/下),官方建议命名为:applicationContext.xml,我们为了方便做多项测试,因此就故意起个别的名字,比如:applicationContextTest1.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="myUser1" class="test1.User">
        <property name="name" value="songxingzhu"/>
        <property name="age" value="10"/>
    </bean>

    <!--方式二:非静态工厂创建-->
    <bean id="userFactory" class="test1.UserFactory"/>
    <!--使用scope设置为prototype(默认为singleton)让每次产生新实例-->
    <bean id="myUser2" factory-bean="userFactory" factory-method="createUser" scope="prototype">
        <property name="name" value="修改后的Name"/>
    </bean>

    <!--方式三:静态方法创建-->
    <bean id="myUser3" class="test1.UserStaticFactory" factory-method="createUser"></bean>

    <!--构建函数的情况一:普通参数 -->
    <bean id="myStudent1" class="test1.Student">
        <constructor-arg name="name" value="Sindrol"/>
        <constructor-arg name="age" value="23"/>
    </bean>
    <!--构建函数的情况二:Bean -->
    <bean id="myStudent2" class="test1.Student">
        <constructor-arg name="user" type="test1.User" ref="myUser3"/>
    </bean>
    <!--构建函数的情况三:Map -->
    <bean id="myStudent3" class="test1.Student">
        <constructor-arg name="map">
            <map key-type="java.lang.String" value-type="java.lang.String">
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
            </map>
        </constructor-arg>
    </bean>
    <!--构建函数的情况四:List -->
    <bean id="myStudent4" class="test1.Student">
        <constructor-arg name="users">
            <array>
                <ref bean="myUser1"/>
                <ref bean="myUser2"/>
            </array>
        </constructor-arg>
    </bean>
</beans>

 

   6、调用Spring框架

  (1)调用代码:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test1.Student;
import test1.User;

public class BeanTest {
    @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContextTest1.xml");
        User myUser1 = (User) context.getBean("myUser1");
        System.out.println(myUser1);
        User myUser2 = (User) context.getBean("myUser2");
        System.out.println(myUser2);
        User myUser2_2 = (User) context.getBean("myUser2");
        System.out.println("[user2==myUser2_2]:" + (myUser2 == myUser2_2));
        User myUser3 = (User) context.getBean("myUser3");
        System.out.println(myUser3);

        Student student1 = (Student) context.getBean("myStudent1");
        System.out.println(student1);
        Student student2 = (Student) context.getBean("myStudent2");
        System.out.println(student2);
        Student student3 = (Student) context.getBean("myStudent3");
        System.out.println(student3);
        Student myStudent4 = (Student) context.getBean("myStudent4");
        System.out.println(myStudent4);


    }
}

  (2)测试结果:

"C:\\Program Files\\Java\\jdk1.8.0_161\\bin\\java" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\\Application\\DevTools\\JetBrains\\IntelliJ IDEA 2018.1\\lib\\idea_rt.jar=9042:D:\\Application\\DevTools\\JetBrains\\IntelliJ IDEA 2018.1\\bin" -Dfile.encoding=UTF-8 -classpath "D:\\Application\\DevTools\\JetBrains\\IntelliJ IDEA 2018.1\\lib\\idea_rt.jar;D:\\Application\\DevTools\\JetBrains\\IntelliJ IDEA 2018.1\\plugins\\junit\\lib\\junit-rt.jar;D:\\Application\\DevTools\\JetBrains\\IntelliJ IDEA 2018.1\\plugins\\junit\\lib\\junit5-rt.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\charsets.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\deploy.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\access-bridge-64.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\cldrdata.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\dnsns.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\jaccess.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\jfxrt.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\localedata.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\nashorn.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\sunec.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\sunjce_provider.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\sunmscapi.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\sunpkcs11.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\ext\\zipfs.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\javaws.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\jce.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\jfr.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\jfxswt.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\jsse.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\management-agent.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\plugin.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\resources.jar;C:\\Program Files\\Java\\jdk1.8.0_161\\jre\\lib\\rt.jar;D:\\Projects\\JavaProjects\\StudyDemo\\SpringDemo\\target\\test-classes;C:\\Users\\Sindrol\\.m2\\repository\\org\\springframework\\spring-context\\5.0.5.RELEASE\\spring-context-5.0.5.RELEASE.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\springframework\\spring-aop\\5.0.5.RELEASE\\spring-aop-5.0.5.RELEASE.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\springframework\\spring-beans\\5.0.5.RELEASE\\spring-beans-5.0.5.RELEASE.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\springframework\\spring-core\\5.0.5.RELEASE\\spring-core-5.0.5.RELEASE.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\springframework\\spring-jcl\\5.0.5.RELEASE\\spring-jcl-5.0.5.RELEASE.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\springframework\\spring-expression\\5.0.5.RELEASE\\spring-expression-5.0.5.RELEASE.jar;C:\\Users\\Sindrol\\.m2\\repository\\junit\\junit\\4.12\\junit-4.12.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\hamcrest\\hamcrest-core\\1.3\\hamcrest-core-1.3.jar;C:\\Users\\Sindrol\\.m2\\repository\\org\\projectlombok\\lombok\\1.16.20\\lombok-1.16.20.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 BeanTest,test1
五月 05, 2018 7:47:45 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@22a71081: startup date [Sat May 05 19:47:45 CST 2018]; root of context hierarchy
五月 05, 2018 7:47:45 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContextTest1.xml]
User(name=songxingzhu, age=10)
User(name=修改后的Name, age=12)
[user2==myUser2_2]:false
User(name=张五, age=22)
Student(name=Sindrol, age=23, users=null, user=null, map=null)
Student(name=另外一个有参数构建Name1, age=2, users=null, user=User(name=张五, age=22), map=null)
Student(name=另外一个有参数构建Name2, age=33, users=null, user=null, map={key1=value1, key2=value2})
Student(name=另外一个有参数构建Name2, age=33, users=[User(name=songxingzhu, age=10), User(name=修改后的Name, age=12)], user=null, map=null)

 

 

以上是关于使用Spring框架入门一:基于XML配置的IOC/DI的使用的主要内容,如果未能解决你的问题,请参考以下文章

Spring框架[一]——spring概念和ioc入门(ioc操作xml配置文件)

Spring 框架的概述以及Spring中基于XML的IOC配置

Spring 从入门到精通系列 07——基于XML与注解方式的IOC案例编写

框架 day36 Spring3 入门,DI依赖注入,装配bean基于xml/注解, 整合Junit4,配置约束自动提示

Spring(概念和ioc入门ioc操作xml配置文件)

Spring框架介绍及使用