在IntelliJ IDEA上使用Maven创建Spring项目HelloWorld

在IntelliJ IDEA上使用Maven创建Spring项目HelloWorld

新建一个Maven 项目
在这里插入图片描述
下一步
在这里插入图片描述
选择Maven,OK.

项目结构
+
pom.xml

  <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.2.0.RELEASE</version>
 </dependency>

创建类
HelloWorld

package com.spring.controller;

/**
 * Created by 逸足天涯
 * Date: 2019/10/15.
 * Time: 9:30
 */
public class HelloWrold {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void say(){
        System.out.println("hello :" + name);
    }
}

传统方式调用类

public class App {
    public static void main(String[] args) {   //传统方式调用
        HelloWrold helloWrold = new HelloWrold();
        helloWrold.setName("Hello! ");
        helloWrold.say();
    }
}

使用Spring 框架
配置Spring 配置文件
File —new — XML Configuration File—Spring Config—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="helloWorld" class="com.spring.controller.HelloWrold">
        <property name="name" value="Spring 5.2"></property>
    </bean>
</beans>

使用Spring 框架IOC获取对象

package com.spring;

import com.spring.controller.HelloWrold;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {   //传统方式调用
        HelloWrold helloWrold = new HelloWrold();
        helloWrold.setName("Hello! ");
        helloWrold.say();
    
        // 使用Spring 框架
        // 1.创建Spring IOC 对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/ApplicationContext.xml");
        //2.从IOC 容器中获得Bean 实例
        //getBean 方法参数值对应ApplcitionContext 中需要创建对象的id
        HelloWrold helloWorld = (HelloWrold)applicationContext.getBean("helloWorld");
        helloWorld.say();
    }
}

结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值