首页 > 其他分享 >Spring(四):HelloSpring

Spring(四):HelloSpring

时间:2022-09-19 14:25:12浏览次数:57  
标签:xml XML ApplicationContext Spring HelloSpring public str class

上一篇学习了控制反转(IoC)的本质和具体实现方法,这次我们就学习写一个小的项目来体验这个过程。

一、项目构建

1.Maven依赖(导包)

<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.23</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

只导入第一个spring-webmvc即可,junit只是为了方便测试。

2.写一个pojo:Hello

package com.jms.pojo;

public class Hello {
    private  String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

3.基于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="..." 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>

The id attribute is a string that identifies the individual bean definition.

The class attribute defines the type of the bean and uses the fully qualified classname.

id是标识单个Bean定义的字符串,class是定义Bean的类型并使用全限定类名。

下面看我们需要配置的XML:

(对于XML文件的名字无特殊要求,这里我们命名为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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
    在java中构造一个对象需要:
    类型 对象名 = new 类型();
    Hello hello = new Hello();

    下面的id=对象名
    class=类型
    property标签通过set方法注入,所以pojo中必须有set方法,其中value代表值,ref代表已经配置好的对象
    -->
    <bean id="hello" class="com.jms.pojo.Hello">
        <property name="str" value="Hello Spring"/>
    </bean>

</beans>

二、测试

在测试之前我们需要知道怎么使用,官方给出了具体的使用方法:

实例化容器

提供给构造函数的一个或多个位置路径是资源字符串,允许容器从各种外部资源(如本地文件系统、Java 等)加载配置元数据。ApplicationContext CLASSPATH

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

使用容器

这是高级工厂的接口,能够维护不同 Bean 及其依赖项的注册表。通过使用 该方法 ,您可以检索 Bean 的实例。ApplicationContextT getBean(String name, Class<T> requiredType)

允许您读取 Bean 定义并访问它们,如以下示例所示:ApplicationContext

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

通过上述官方给出的使用例子,我们不难知道我们首先要通过传入XML的文件名实例化容器,并且通过getBean来获取我们的对象。

实例化容器的方法中,可以传入一个XML的文件名,也可以传入多个;getBean中的字符串传入的是XML文件中配置的bean的id,传入的class就是对象对应的类。

知道了具体的使用,下面我们就来实现:

@Test
    public void HelloSpring() {
        //实例化容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        //通过容器获取对象
        Hello hello = applicationContext.getBean("hello", Hello.class);
        System.out.println(hello);
    }

测试结果:

 没有问题。

 

既然HelloSpring没有问题,我们就完善一下一开始用于学习IoC基本原理的一个项目。

先看一下项目框架:

 

 由于依赖已经导入,在此我么就直接去配置XML文件,这里我们配置两个XML文件:

dao.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="usrDaoImpl" class="com.jms.dao.UserDaoImpl"></bean>
    <bean id="userDaoMysqlImpl" class="com.jms.dao.UserDaoMysqlImpl"></bean>
    <bean id="userDaoOracleImpl" class="com.jms.dao.UserDaoOracleImpl"></bean>

</beans>

service.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">

    <import resource="dao.xml"/>
    <bean id="userServiceImpl" class="com.jms.service.UserServiceImpl">
        <property name="userDao" ref="userDaoMysqlImpl"/>
    </bean>

</beans>

可以看到上面service.xml中有一个import标签引用了dao.xml,这是因为下面用到了dao.xml里面的bean,所以需要import引用,如果是在同一个xml文件下则不需要。

接下来测试:

 @Test
    public void UserService() {
        //实例化容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("dao.xml", "service.xml");
        //获取对象
        UserService userService = applicationContext.getBean("userServiceImpl", UserServiceImpl.class);
        userService.getUser();
    }
测试结果:

 

 我们修改service.xml中的ref都会得到不同的结果:

<property name="userDao" ref="usrDaoImpl"/>

<property name="userDao" ref="userDaoOracleImpl"/>

 

 可见,我们不需要对代码进行修改,只需修改配置文件就可以实现不同的需求。

 

(本文仅作个人学习用,如有纰漏敬请指正)

标签:xml,XML,ApplicationContext,Spring,HelloSpring,public,str,class
From: https://www.cnblogs.com/jmsstudy/p/16706592.html

相关文章

  • SpringCloud框架开发
     1.是什么微服务 是一种架构模式,他提倡将单一应用程序划分一组小的服务,服务之间的相互配合、互相协调。 2.SpringCloud简介 SpringClound等于分布式微服务架构......
  • Spring 注册 Bean 在配置中的定义和使用 Autowired
    因为项目的需要,我们使用了一个第三方的电子邮件库,但是我们希望把这个库在项目中注册成Bean然后随时在其他地方使用。Configuration在哪里注册?我们通常可以在Configur......
  • Spring源码分析-Bean实现
    实现SpringBean功能定义扫描路径创建ApplicationContext类packagecom.smile.spring;publicclassApplicationContext{}采用配置类加注解实现配置功能创建......
  • springboot拦截器
    packagecom.module.interceptor;importlombok.Data;importlombok.extern.slf4j.Slf4j;importorg.springframework.context.annotation.Configuration;importorg......
  • springboot内置tomcat配置本地文件夹的映射路径
    例如要访问的本地路径是D盘下的PersonalHomePage目录的某个图片1importorg.springframework.context.annotation.Configuration;2importorg.springframework.web.......
  • Spring(三):IoC的本质
    一、图例  对照上面的图,我们回想上一篇中几个代码的实现,在没有set注入之前,代码运行完全由Service层控制,用户没有选择权,选择权在程序员手中;但是使用set注入之后,用户可......
  • springboot中解析JSON参数
    解析psot请求中的JSON参数Map<String,String>attrMap=newHashMap<String,String>();BufferedReaderstreamReader=null;try{streamReader=newBufferedRead......
  • Java【SpringBoot】——添加测试依赖
    在pom.xml添加依赖1<dependency>2<groupId>org.springframework.boot</groupId>3<artifactId>spring-boot-starter-test</artifactId>......
  • springboot集成mybatis获取插入数据的主键
    问题:我们想在插入一条数据后同时能够返回这条数据在表中的id,Mybatis提供了@SelectKey注解。student为数据表,主键自增SelectKey的四个属性:selectKey会将SELECTLAS......
  • SpringBoot集成Mybatis 实现InsertOrUpdate功能
    需求场景在项目开发过程中,难免会遇到这样的场景:对一张表,当数据不存在的时候,进行insert插入操作;数据存在的时候,进行update更新操作;下面就来使用Mybatis的InsertOrUpdate功......