返回介绍

4.4 应用 @Autowired 和 @Service 进行依赖注入

发布于 2025-04-22 20:09:59 字数 5480 浏览 0 评论 0 收藏

使用 Spring 框架的一个好处是容易进行依赖注入。毕竟,Spring 框架一开始就是一个依赖注入容器。将依赖注入到 Spring MVC 控制器的最简单方法是,通过注解 @Autowired 到字段或方法。Autowired 注解类型属于 org.springframework.beans.factory.annotation 包。

此外,为了能作为依赖注入,类必须要注明为 @Service。该类型是 org.springframework. stereotype 包的成员。Service 注解类型指示类是一个服务。此外,在配置文件中,还需要添加一个<component-scan/>元素来扫描依赖基本包。

< context:component-scan base-package="dependencyPackage"/>

下面以 annotated2 应用进一步说明 Spring MVC 如何应用依赖注入。在 annotated2 应用程序中,ProductController 类(见清单 4.6)已经不同于 annotated1 中的类。

清单 4.6 annotated2 中的 ProductController 类

package controller;
import java.math.BigDecimal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import domain.Product;
import form.ProductForm;
import service.ProductService;

@Controller
public class ProductController {
  private static final Log logger = LogFactory
      .getLog(ProductController.class);

  @Autowired
  private ProductService productService;

  @RequestMapping(value = "/input-product ")
  public String inputProduct() {
    logger.info("inputProduct called");
    return "ProductForm";
  }

  @RequestMapping(value = "/save-product ", method = RequestMethod.POST)
  public String saveProduct(ProductForm productForm,
      RedirectAttributes redirectAttributes) {
    logger.info("saveProduct called");
    // no need to create and instantiate a ProductForm
    // create Product
    Product product = new Product();
    product.setName(productForm.getName());
    product.setDescription(productForm.getDescription());
    try {
      product.setPrice(new BigDecimal(productForm.getPrice()));
    } catch (NumberFormatException e) {
    }

    // add product
    Product savedProduct = productService.add(product);

    redirectAttributes.addFlashAttribute("message",
        "The product was successfully added.");
    return "redirect:/product-view/" + savedProduct.getId();
  }

  @RequestMapping(value = "/view-product/{id}")
  public String viewProduct(@PathVariable Long id, Model model) {
    Product product = productService.get(id);
    model.addAttribute("product", product);
    return "ProductView";
  }
}

与 annotated1 中相比,annotated2 中的 ProductController 类做了一系列的调整。首先是在如下的私有字段上增加了 @Autowired 注解:

@Autowired
private ProductService productService

ProductService 是一个提供各种处理产品的方法的接口。为 productService 字段添加 @Autowired 注解会使 ProductService 的一个实例被注入到 ProductController 实例中。

清单 4.7 和清单 4.8 分别显示了 ProductService 接口及其实现类 ProductServiceImpl。注意,为了使类能被 Spring 扫描到,必须为其标注 @Service。

清单 4.7 ProductService 接口

package service
import domain.Product;
public interface ProductService {
  Product add(Product product);
  Product get(long id);
}

清单 4.8 ProductServiceImpl 类

package service;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import domain.Product;

@Service public class ProductServiceImpl implements ProductService { private Map< Long, Product> products = new HashMap< Long, Product>(); private AtomicLong generator = new AtomicLong(); public ProductServiceImpl() { Product product = new Product(); product.setName("JX1 Power Drill"); product.setDescription( "Powerful hand drill, made to perfection"); product.setPrice(new BigDecimal(129.99)); add(product); } @Override public Product add(Product product) { long newId = generator.incrementAndGet(); product.setId(newId); products.put(newId, product); return product; } @Override public Product get(long id) { return products.get(id); } }

如清单 4.9 所示,annotated2 的 Spring MVC 配置文件中有两个<component-scan/>元素:一个用于扫描控制器类,另一个用于扫描服务类。

清单 4.9 Spring MVC 配置文件

< ?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:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/springcontext.xsd">

  < context:component-scan base-package="controller"/>
 < context:component-scan base-package="service"/> < mvc:annotation-driven/> < mvc:resources mapping="/css/**" location="/css/"/> < mvc:resources mapping="/*.html" location="/"/> < bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> < property name="prefix" value="/WEB-INF/jsp/"/> < property name="suffix" value=".jsp"/> < /bean> < /beans>

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。