zoukankan      html  css  js  c++  java
  • Spring基础02——Spring HelloWorld

    1.首先我们来创建一个HelloWorld类,通过Spring来对这个类进行实例化

     1 package com.wzy.lesson1;
     2 
     3 /**
     4  * @author wzy
     5  * @version 1.0
     6  * @date 2019/5/5 23:46
     7  */
     8 public class HelloWorld {
     9     private String name;
    10 
    11     public void setName(String name) {
    12         System.out.println("setName : " +  name);
    13         this.name = name;
    14     }
    15 
    16     public void hello() {
    17         System.out.println("Hello " + name);
    18     }
    19 
    20     public HelloWorld() {
    21         System.out.println("HelloWorlds Constructor...");
    22     }
    23 }

    2.之后在项目的类路径下,我是在resources文件夹下创建

    spring.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-->
        <bean id="helloWorld" class="com.wzy.lesson1.HelloWorld">
            <!--通过setName方法注入-->
            <property name="name" value="Spring"/>
        </bean>
    </beans>

    3.编写测试类创建HelloWorld类实例

     1 private static void testHelloWorld2() {
     2         //1.创建Spring的IOC容器对象
     3         ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
     4 
     5         //2.从IOC容器中获取Bean实例
     6 //        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
     7         //用类型获取,但是如果由多个接口的实现类,那么容器就不知道应该为我们返回哪个实例
     8         HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
     9 
    10         //3.调用hello方法
    11         helloWorld.hello();
    12     }

    这里使用Spring的IOC容器ApplicationContext的实现类ClassPathXmlApplicationContext对bean进行获取,这里获取bean的方式有两种:

    第一种:通过bean的id进行获取

    1 HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");

    第二种:通过bean的class进行获取

    1 HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

    推荐使用第一种,因为在使用类名.class方式时,如果配置了两个HelloWorld类的bean那么,Spring容器将会抛出异常,因为容器无法确定你要获取的是哪一个bean,所以,如果要使用第二种的话,那么就要保证配置文件中只配置了一个HelloWorld类的bean,如果存在多个就会抛出一下异常:

    测试结果:成功创建HelloWorld类的实例

  • 相关阅读:
    前端学PHP之错误处理
    mysql数据库学习目录
    前端学数据库之存储
    前端学数据库之函数
    用shell脚本监控进程是否存在 不存在则启动的实例
    在notepad++里面使用正则表达式替换掉所有行逗号前面内容
    mysql合并 两个count语句一次性输出结果的方法
    硬件中断和DPC一直占40-52%左右 解决方法
    解决secureCRT 数据库里没有找到防火墙 '无' 此会话降尝试不通过防火墙进行连接。
    Java eclipse下 Ant build.xml实例详解 附完整项目源码
  • 原文地址:https://www.cnblogs.com/fengyun2019/p/10819115.html
Copyright © 2011-2022 走看看