在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();
}
}
结束。