Spring学习笔记(一)

1.在搭建好maven项目后(如果不清楚如何搭建maven项目的可以参考我的上一篇博客),项目的目录结构如下图所示:

接下来需要添加spring(用maven管理项目的优点是:1. 借助maven,可以将jar包保存到“仓库”中,有需要使用的工程直接引用相关的包即可,而无需手动复制粘贴到lib下。2.以前的jar包都是提前下好的,如果本地没有还得重新下载,通过maven可以联网下载相关包3.maven可以将一个项目拆分为多个工程,实现“多人开发”)

 

2.在maven中导入spring框架。

首先去project settings在module 添加spring组件

但是你会在下方看到一个黄色警告。

点击fix

然后下载相应的spring的jar包,即可运行spring框架。

然后你还需要添加依赖jar包可以直接在pom.xml文件右击,点击generate

然后点击Dependency

在搜索框搜索你想要的框架名 ,然后添加即可:

得到如下依赖:

<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-core</artifactId>

  <version>5.0.7.RELEASE</version>

</dependency>

<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-beans</artifactId>

  <version>5.0.7.RELEASE</version>

</dependency>

<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-context</artifactId>

  <version>5.0.7.RELEASE</version>

</dependency>

 

然后我们在src下的main下新建resources文件夹,然后右键文件夹set as root resources,在resources下新建配置文件applicationContext.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="helloBean" class="com.ray.controller.HelloWorld">

      <property name="name" value="RayTseng"/>

</bean>

</beans>

 

在main文件夹下新建一个java文件夹,然后在java下新建一个包,这里我就随便建了一个包com.ray.controller,然后在该包下面新建两个class文件HelloWorld 以及App文件。

接下来通过这两个class文件,来完成基于spring框架的hello world程序。

 

public class HelloWorld {

   private String name;

 

    public void printHello() {

        System.out.println("Spring 4 : Hello ! " + name);

    }

 

    public void setName(String name) {

        this.name = name;

    }

}

 

 

package com.ray.controller;

import  org.springframework.context.ApplicationContext;

import  org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext(

                "applicationContext.xml");

        HelloWorld obj = (HelloWorld) context.getBean("helloBean");

        obj.printHello();

    }

}

 

运行app.class文件得到,证明spring框架运行成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值