创建第一个spring HelloWorld程序

什么是spring

spring是一个轻量级的DI/IOC和AOP容器的开源框架。
DI:Dependency Injection(依赖注入)
IoC:inverse of control(控制反转)
AOP: Aspect-Oriented Programming(面向切面编程)
DI指spring创建对象的过程中,将对象依赖属性(简单值,集合,对象)通过配置设置给该对象
IoC:控制反转,就是将原本在程序中手动创建对象的控制权交给spring容器来做。
AOP:aop采取横向抽取机制,将分散在各个地方的重复的代码提取出来,在编译运行时将这些代码应用到需要执行的地方。

导入依赖的jar包

使用spring,首先导入jar包
spring-core 使用spring的核心jar包
spring-context
spring-beans
commons-logging

创建配置文件

创建名为applicationContext.xml的配置文件,使用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
id/name 给bean元素设定标识 id唯一,name不唯一
class 把哪一个类交给spring容器去管理
-->
<bean id="helloWorld" name="hello world helloWorld2,helloWorld3;helloWorld4" class="com.teng.HelloWorld" scope="prototype">
</bean>
 <bean id = "hw" class="com.teng.HelloWorld" scope="prototype">
  <!--
  第二种形式,通过有参构造注入,前提:必须有有参构造
  index 通过参数的索引注入
  type  通过参数的类型注入
  -->
 <!-- <constructor-arg index="0" value="1"></constructor-arg>
  <constructor-arg index="1" value="向阳"></constructor-arg>-->
  <constructor-arg type="int" value="23"></constructor-arg>
  <constructor-arg type="java.lang.String" value="菲菲"></constructor-arg>

测试类

package com.teng;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    @org.junit.Test
    public void test1(){
       //spring 从spring容器中获取对象
       //读取spring配置文件,创建bean工厂
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");
        HelloWorld hell = (HelloWorld) beanFactory.getBean("helloWorld");
        HelloWorld hell1 = (HelloWorld) beanFactory.getBean("hello");
        //HelloWorld hell2 =  beanFactory.getBean(HelloWorld.class);
        HelloWorld hell3 = beanFactory.getBean("hw",HelloWorld.class);
        hell.sayHell();
    }
}

beanFactory可以通过三种方法获取对象
1,beanFactory.getBean(“id名/name名”);通过bean名获取
2,beanFactory.getBean(对象.class);通过class获取
3,beanFactory.getBean(“id名/name名”,对象.class);通过name+class 官方推荐

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值