本过程通过IDEA+Maven的方式来展示,Spring的hello world;
- 新建spring项目 (java project类型)
- 使用该项目用maven
右击之后选择这个
- 编写
pom.xml
,加入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springdemo</groupId>
<artifactId>SpringDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.3.RELEASE</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
</dependencies>
</project>
相关依赖已经全部导入进来了。maven管理包的话还是很方便的。
4. 编写service类
package com.springdemo.service;
public class WelcomeService {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void sayHello(){
System.out.println(message);
}
}
- 编写
beans.xml
文件,这个文件就是Java bean,Spring只是帮你创建好了。
<?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="ws" class="com.springdemo.service.WelcomeService">
<property name="message" value="hello world"/>
</bean>
</beans>
bean标签,就是创建一个Java bean。这就是spring的作用和目的。
6. 编写测试类。
package com.springdemo;
import com.springdemo.service.WelcomeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
//创建容器
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
WelcomeService ws = (WelcomeService)ac.getBean("ws");
ws.sayHello();
}