Spring学习使用标签来标记资源(@Component、@Repository、 @Service和@Controller)和用法(包括如何jsp正在使用)...

本文详细介绍了如何在Java项目中使用Spring框架,包括如何配置容器、扫描包、注解组件、注入依赖以及测试方法。同时,文章还讨论了在JSP页面中如何处理业务逻辑,以及如何在类间进行依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,在xml其中新增部分标有下划线的文件,容器初始化的时候需要扫描包

 注意:

a.     包款扫描(下划线部分)一定要加,默认是不扫描整个包。与每一包之间’,’开。如过具有同样的父包,那么我们能够用父包来取代。例如以下划线部分,我们能够用com.bjsxt来取代。

<?

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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /><!-- 自己主动装配一定要 加上此片段--> <context:component-scan base-package="com.bjsxt.dao.impl,com.bjsxt.service,com.bjsxt.model"></context:component-scan> </beans>



b.     在2.5版本号中(@Component@Repository@Service@Controller)四个标签代表同样的含义,以后的版本号中可能会有差别。

c.    在标注组件等资源时候,尽量加上名称比如@Component("stuDaoImpl")

默认的名称是 类名首字母小写。

<pre name="code" class="java">package com.bjsxt.dao.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.*;
import com.bjsxt.model.Student;
@Component("stuDaoImpl")
public class StudentDaoImpl implements StudentDao{
	@Override
	public void StudentSave(Student s) {
          System.out.println("学生被保存!");
		
	}
}

 
  

d.      用法 在set方法或者属性名前增加 @resource(name="stuDaoImpl"),推荐增加名称,默认是依照类型进行查找。比如:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bjsxt.dao.*;
import com.bjsxt.dao.impl.*;
import com.bjsxt.model.*;
@Component("studentService")//声明资源
public class StudentService {
private StudentDao studentDao;
public StudentDao getStudentDao() {
	return studentDao;
}
@Resource(name="stuDaoImpl")//注入
public void setStudentDao(StudentDao studentDao) {
	this.studentDao = studentDao;
}
public void add(Student s)
{
	this.studentDao.StudentSave(s);
}

e. 測试方式依旧和之前的注入方式一样,注意这里的

Studentstudent=(Student)ctx.getBean("student");是我们用标签在student类中声明的@Component("student")。

Spring容器会能通过ctx(相当于beanFactory)找到。

package com.bjsxt.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.Student;

public class StudentServiceTest {

	@Test
	public void test() {
		System.out.println("程序执行之前....");
		ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
		System.out.println("程序执行開始....");
		StudentService sService=(StudentService)ctx.getBean("studentService");
		
		Student student=(Student)ctx.getBean("student");
		Student student2=(Student)ctx.getBean("student");
		System.out.println(student2==student);
		sService.add(student);
	}
}

f.   在jsp页面须要处理业务,有java代码须要spring注入service。

须要如今想要获取的类前加标签

@Component("docrelationService")首先jsp页面导入

<%@page import="org.springframework.context.ApplicationContext"%>
<%@pageimport="org.springframework.web.context.support.WebApplicationContextUtils"%>

获取spring注入

<%
        ApplicationContext context =WebApplicationContextUtils
             .getWebApplicationContext(application);

           DocrelationServicedocrelationService = (DocrelationService) context
             .getBean("docrelationService");

%>

g.  

 假如类Aspring容器管理,在类B中引用A,假设想在B中的A是由spring容器创建的,有两种方法:

     a).B也由spring容器管理(即类B前有@compoment(b)标签),并注入A,BeanFactory.getBean("b") 得到B实例,就可以(推荐).

     b).B不由spring容器管理,在类B中用代码 (ABeanFactory.getBean("a")得到A实例,就可以.(不推荐,会产生两个beanFactory由于在类B中须要用BeanFactory,所以我们必须在Bnew一个)

c)B创建实例时候假设採用a)方法,决不能採用B b=new B();的方式,否则会报nullpoint异常。

d)ClassPathXmlApplicationContext建立在beanFactory基础之上,非常少有人直接使用。

測试代码:

package com.bjsxt.service;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.Student;

public class StudentServiceTest {

	@Test
	public void test() {
		System.out.println("程序执行之前....");
		//BeanFactory ctx=new ClassPathXmlApplicationContext("beans.xml");
		//ClassPathXmlApplicationContext建立在beanFactory基础之上,非常少有人直接使用。

ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");//直接获取spring容器 System.out.println("程序执行開始...."); StudentService sService=(StudentService)ctx.getBean("studentService");//StudentService相当于类B //StudentService sService=new StudentService(); Student student=(Student)ctx.getBean("student"); Student student2=(Student)ctx.getBean("student"); System.out.println(student2==student); sService.add(student); } }





版权声明:本文博客原创文章,博客,未经同意,不得转载。

<think>好的,我现在需要回答关于Spring MVC中@Controller注解的作用的问题。用户之前已经询问过Java的实现,现在转向Spring MVC的具体注解,说明他们可能在学习Spring框架,特别是Web层的内容。我需要确保回答清晰且适合他们的学习阶段。 首先,我应该回忆@Controller的基本作用。@ControllerSpring MVC中用来标记一个作为控制层的组件,处理HTTP请求。需要解释它如何与@RequestMapping或其他注解配合,处理不同的请求方法(GET、POST等)。 然后,考虑用户可能的背景。他们可能已经了解MVC模式,所以需要将@Controller与ModelView联系起来,说明它在MVC中的角色。可能需要提到它如何接收请求参数,调用服务层,返回视图名称或数据。 另外,用户可能想知道@Controller@RestController的区别,但问题中没有提到,是否需要简要说明?可能先专注@Controller本身,如果有必要可以稍微提及,但避免偏离主题。 接下来,我应该给出一个简单的代码示例,说明如何在使用@Controller,并定义一个处理请求的方法。例如,一个返回视图名称的方法,或者使用@ResponseBody返回JSON数据。这样可以展示注解的实际应用。 还要提到Spring的组件扫描机制,@Controller作为@Component的派生注解,会被自动扫描并注册为Bean,这样DispatcherServlet才能将请求路由到对应的控制器方法。 另外,需要强调@Controller处理的是Web请求,通常与视图技术(如JSP、Thymeleaf)结合使用,而@RestController更适合RESTful Web服务,返回JSON/XML。但根据用户的问题,重点放在@Controller上。 可能用户会混淆@Controller@Service@Repository,是否需要说明?可能不需要,但可以提到它们在Spring中的不同层次,@Controller属于Web层。 需要确保术语准确,比如处理请求的方法通常称为处理器方法或请求处理方法,使用@RequestMapping或其变体(@GetMapping等)。 最后,总结@Controller的主要用途,强调其在Spring MVC中的核心地位,帮助分离关注点,实现MVC架构。</think>在 Spring MVC 中,**`@Controller`** 是一个核心注解,用于标记一个作为 **Web 请求的控制器**,负责处理用户请求(HTTP 请求)并返回响应(如视图或数据)。它是 Spring MVC 实现 **MVC 模式**(Model-View-Controller)的关键组件。 --- ### **@Controller 的核心作用**: 1. **标识控制器** 通过 `@Controller` 注解标记会被 Spring 容器识别为控制器,DispatcherServlet 会将请求路由到该中的方法。 2. **处理 HTTP 请求** 结合 `@RequestMapping`、`@GetMapping`、`@PostMapping` 等注解,定义具体的请求处理逻辑。 ```java @Controller public class UserController { @GetMapping("/users") public String listUsers(Model model) { List<User> users = userService.getAllUsers(); model.addAttribute("users", users); // 将数据传递给视图 return "user-list"; // 返回视图名称(如 user-list.jsp 或 Thymeleaf 模板) } } ``` 3. **与视图技术集成** 返回的视图名称(如 `"user-list"`)会被视图解析器(如 `InternalResourceViewResolver`)解析为具体的视图(如 JSP、Thymeleaf 模板)。 4. **接收请求参数** 通过方法参数自动绑定 HTTP 请求中的参数、路径变量、表单数据等: ```java @PostMapping("/users/{id}") public String updateUser(@PathVariable Long id, @RequestParam String name) { // 处理参数并执行业务逻辑 return "redirect:/users"; } ``` 5. **支持数据绑定验证** 结合 `@ModelAttribute` `@Valid` 注解,实现表单数据的绑定校验。 --- ### **@Controller vs @RestController**: - **`@Controller`**: 通常用于传统的 MVC 应用,返回**视图名称**(如 HTML 页面),需要配合视图解析器使用。 - **`@RestController`**: 是 `@Controller` + `@ResponseBody` 的组合,用于 RESTful API,直接返回**数据**(如 JSON/XML),无需视图解析。 --- ### **关键特性**: - **自动扫描**: 在 Spring 配置中启用组件扫描(`<context:component-scan>` 或 `@ComponentScan`)后,`@Controller` 会被自动注册为 Bean。 - **松散耦合**: 控制器只负责协调请求响应,具体业务逻辑委托给 Service 层。 - **灵活性**: 支持返回视图、重定向、文件下载等多种响应型。 --- ### **示例代码**: ```java @Controller @RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; // 处理 GET /products/123 @GetMapping("/{id}") public String getProduct(@PathVariable Long id, Model model) { Product product = productService.findById(id); model.addAttribute("product", product); return "product-detail"; // 对应 product-detail.html 模板 } // 处理 POST /products @PostMapping public String createProduct(@ModelAttribute Product product) { productService.save(product); return "redirect:/products"; // 重定向到列表页 } } ``` --- ### **总结**: `@Controller` 是 Spring MVC 中定义控制器的核心注解,它的作用包括: 1. 标识一个为请求处理器。 2. 通过方法注解绑定具体的 URL HTTP 方法。 3. 接收并处理请求参数,执行业务逻辑。 4. 返回视图或重定向指令,实现 MVC 模式中的“控制层”职责。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值