【JavaEE】Springmvc+Spring整合及example

这一篇在前一篇Springmvc的基础上,加上Spring。Spring的主要用途叫做控制反转(依赖注入,IoC/DI)和面向切面的编程(AOP),本文只介绍IoC,因为AOP主要的应用场景是记录日志,暂时不需要,等我要整合的几个框架都整合在一起的时候再加上。

pom.xml不需要新添加任何东西,因为spring-core等包都在导入spring-webmvc的时候作为依赖项被导入了,所以直接来看配置。

1. web.xml

Spring要在程序需要某个对象的时候,把这个对象的实例注入进去,默认情况下,Spring以单例的形式维护了所有需要注入的对象的实例,哪里需要就把对应的实例给哪里,Spring自己对实例、程序运行的管理构成了Spring自己的容器,第一步就是要在web.xml中注册,初始化这个容器:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/META-INF/applicationContext.xml</param-value>
</context-param>
    
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

这里注册一个ContextLoaderListener,并指定spring配置文件的位置,在类路径下的/META-INF/applicationContext.xml,现在在maven的resources资源包下,即src/main/resources下面创建目录META-INF,在这个目录下创建applicationContext.xml,这个文件就是spring的配置文件。

2. applicationContext.xml

applicationContext.xml是spring的核心配置文件,spring4和之前版本的一个很大的区别,就是推荐情况下bean不是在xml文件中配置,而是通过扫描固定annotation的类,根据对象的类型或者名字自动加载,以前在applicationContext.xml需要配置大量的bean,现在不用了,但是仍然要告诉spring,去哪个包下面找这些带着annotation等着被扫描的类:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <context:component-scan base-package="org.zhangfc.demo4ss.service"/>

</beans>

前面这一堆东西先不用管,直接粘贴好了,其实很多现在还用不到,不过也没有关系,先放在这好了,真正有用的配置就一句话,需要spring管理的类,请到org.zhangfc.demo4ss.service下面去找。

3. UserService.java

下面写一个服务类,用来获得注册用户列表,创建package:org.zhangfc.demo4ss.service,在下面创建接口UserService,写一个方法获取所有用户名。

public interface UserService {
    public List<String> getAllUsernames();
}

再创建一个类UserServiceImpl,实现这个接口:

@Service
public class UserServiceImpl implements UserService {

    public List<String> getAllUsernames() {
        List<String> users = new ArrayList<String>();
        users.add("zhangsan");
        users.add("lisi");
        users.add("wangwu");
        return users;
    }

}

这里比较关键的就是@Service这个annotation,它告诉Spring,我是一个Service,需要你来管理我。

4. HomeController

回到控制器里,上一篇文章我写了一个方法叫json来返回一个json对象,现在改一下这个方法,通过前面写的UserService来获取用户列表并返回给客户端。

首先定义一个类的全局变量UserService:

@Autowired
private UserService userService;

这里要注意的是Autowire这个annotation,它是为了告诉spring,这个对象没有实例化,需要你来注入一个UserService的实例,那问题就是,UserSerivce是一个接口,不指定谁知道你想用的实现类是哪个,Spring会首先看自己的容器里有没有一个叫做userService的对象(刚才那个UserServiceImpl的对象名字就叫做userServiceImpl),如果找不到就在配置文件里配置的路径下面寻找UserService的实现类,找到了就把它的对象拿过来,除此之外刚才Service那个annotation还可以指定一个value:

@Service("userService")

这样一来,对于UserServiceImpl这个类的实例,Spring给它起的名字就不是userServiceImpl了,而是userService,如果某个接口的实现类有多个,就可以使用这种方法来指定用哪个实现类,个人认为,如果每个接口都只有一个实现类,那么这么做确实很方便,但如果有多个实现类并且可能会更换的话,就不如配置文件明了了(当然了,现在这种方式也可以把参数抽出来放到配置文件里,不过还是麻烦一些)。

然后修改json方法:

@RequestMapping("/json")
@ResponseBody
public List<String> json(){
    return userService.getAllUsernames();
}

Spring在这里的作用就是把HomeController需要的userService注入进来,运行程序,访问http://localhost:8080/demo4springmvc-spring/json:

["zhangsan","lisi","wangwu"]

源码下载

Spring的另一个功能AOP暂且不用,等需要记录日志的时候再写,当然,Spring本身也有很多复杂的机制,后面在具体问题中慢慢介绍。

转载于:https://www.cnblogs.com/smarterplanet/p/4085620.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Spring 6中使用Spring MVC的初始化案例。 1. 首先,确保你的项目中已经包含了Spring MVC和Jakarta Servlet API的依赖项。你可以在Maven或Gradle中添加以下依赖项: ```xml <!-- Maven 依赖项 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.0-M1</version> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>4.0.3</version> <scope>provided</scope> </dependency> ``` ```groovy // Gradle 依赖项 implementation 'org.springframework:spring-webmvc:6.0.0-M1' compileOnly 'jakarta.servlet:jakarta.servlet-api:4.0.3' ``` 2. 在Web应用程序中,需要在web.xml文件中配置Spring MVC的DispatcherServlet。以下是一个基本的web.xml文件示例: ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` 在这个示例中,我们定义了一个名为“dispatcherServlet”的Servlet,并将它映射到根路径“/”。其中,`servlet-class`是Spring MVC的`DispatcherServlet`,`init-param`中的`contextConfigLocation`参数指定了Spring MVC配置文件的位置。 3. 创建Spring MVC配置文件`spring-mvc-config.xml`,并将其放置在WEB-INF目录下。以下是一个基本的Spring MVC配置文件示例: ```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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.example.controller"/> <mvc:annotation-driven/> </beans> ``` 在这个示例中,我们启用了Spring MVC的注解驱动(`<mvc:annotation-driven/>`),并使用`<context:component-scan>`扫描了一个名为`com.example.controller`的包,以寻找注解为`@Controller`的。 4. 创建一个控制器`HelloController`,并使用`@Controller`注解将其标记为Spring MVC控制器。以下是一个基本的控制器示例: ```java package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class HelloController { @GetMapping("/hello") @ResponseBody public String hello() { return "Hello, Spring MVC!"; } } ``` 在这个示例中,我们使用`@Controller`注解将`HelloController`标记为一个Spring MVC控制器,并使用`@GetMapping`注解将`hello()`方法映射到路径`/hello`上。同时,使用`@ResponseBody`注解告诉Spring MVC将方法的返回值作为响应正文返回给客户端。 5. 启动你的Web应用程序,并在浏览器中访问`http://localhost:8080/hello`,你应该可以看到“Hello, Spring MVC!”的响应。 希望这个示例可以帮助你了解如何在Spring 6中使用Spring MVC。如果你还有其他问题,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值