第三章 快速搭建Spring4.x项目

来源:互联网 发布:玄空排盘软件下载 编辑:程序博客网 时间:2024/06/10 19:29

以下操作使用Spring Tool Suite(简称STS,Spring官方推出的基于Eclipse的开发工具)进行操作。

一、新建一个Maven项目

二、修改pom文件,添加对Spring的依赖

<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.example</groupId>  <artifactId>demo2</artifactId>  <version>0.0.1-SNAPSHOT</version>  <properties>    <java.version>1.8</java.version>    <spring.version>4.1.6.RELEASE</spring.version>  </properties>  <dependencies>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>${spring.version}</version>    </dependency>  </dependencies>  <build>    <plugins>        <plugin>            <groupId>org.apache.maven.plugins</groupId>            <artifactId>maven-compiler-plugin</artifactId>            <configuration>                <source>${java.version}</source>                <target>${java.version}</target>            </configuration>        </plugin>    </plugins>  </build></project>

三、编写Service类

package demo2.service;import org.springframework.stereotype.Service;@Servicepublic class DemoService {    public void say(String word) {        System.out.println("Hello " + word);    }   }

四、编写配置类

package demo2.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScan("demo2")public class DIConfig {}

五、创建Spring容器并运行

package demo2;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import demo2.config.DIConfig;import demo2.service.DemoService;public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext(DIConfig.class);        DemoService ds = cxt.getBean(DemoService.class);        ds.say("Spring");        cxt.close();    }}

六、查看运行结果

Hello Spring
0 0
原创粉丝点击