Spring 学习之路(一): 第一个Spring程序

什么是Spring?

简单来讲:
- Spring 是一个开源框架

  • Spring 为简化企业级应用开发而生
  • Spring 是一个 IOC(DI) 和 AOP 容器框架

具体来讲:
- 轻量级:Spring 是非侵入性的 - 基于 Spring 开发的应用中的对象可以不依赖于 Spring 的 API

  • 依赖注入(DI — dependency injection、IOC)
  • 面向切面编程(AOP — aspect oriented programming)
  • 容器: Spring 是一个容器, 因为它包含并且管理应用对象的生命周期
  • 框架: Spring 实现了使用简单的组件配置组合成一个复杂的应用. 在 Spring 中可以使用 XML 和 Java 注解组合这些对象
  • 一站式:在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库 (实际上 Spring 自身也提供了展现层的 SpringMVC 和 持久层的 Spring JDBC)
spring架构图解

mark

  • 注意:使用spring之前我们最好在eclipse里面安装安装 SPRING TOOL SUITE,方便我们后续的开发
构建第一个Spring程序
  • 具体搭建环境看我源代码即可,这里不累述了
  • 测试代码:
    1.构建javaBean
public class HelloWorld {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("set name");
        this.name = name;
    }

    public HelloWorld() {
        System.out.println("hello");
    }
}

2.src目录下配置applicationContext.xml

<!-- 配置bean对象 class:bean的全类名,通过反射的方式在IOC容器中创建Bean的对象,所以要求Bean中必须要有无参构造器 
        id:标识容器中的bean,id值唯一 -->
    <bean id="helloWorld" class="com.zc.cris.HelloWorld">
        <property name="name" value="cris"></property>
    </bean>

3.测试

public class TestSpringIOC {

    public static void main(String[] args) {

        //使用了 Spring 以后,第一和第二步我们就不用自己创建了,由 Spring 框架自动完成,也就是控制翻转的意思(IOC)
        //1. 创建 helloWorld 的对象
        //HelloWorld helloWorld = new HelloWorld();
        //2. 为这个实例对象赋值
        //helloWorld.setName("Spring");


        //1. 创建 spring 的 ioc 容器
        //ApplicationContext 代表IOC容器
        //ClassPathXmlApplicationContext : 是ApplicationContext 接口的实现类,该实现类可以从类路径下加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2. 从 ioc 容器中获取 bean 对象
        //利用id定位到ioc容器中的bean(推荐)
        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");

        //3. 调用这个实例的方法
        System.out.println(helloWorld.getName());
    }
}

console:

mark
- 至此,我们的第一个简单Spring程序就搭建好了

源代码点我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值