能源项目xml文件标签释义--<context:component-scan>

本文通过一个简单示例介绍Spring框架中的注解注入机制。详细解释了如何使用@Service、@Autowired等注解,并展示了如何在Spring配置文件中启用注解注入。
    <context:component-scan base-package="com.xindatai.ibs" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

spring从2.5版本开始支持注解注入,注解注入可以省去很多的xml配置工作。由于注解是写入java代码中的,所以注解注入会失去一定的灵活性,我们要根据需要来选择是否启用注解注入。

我们首先看一个注解注入的实际例子,然后再详细介绍context:component-scan的使用。

如果你已经在用spring mvc的注解配置,那么你一定已经在使用注解注入了,本文不会涉及到spring mvc,我们用一个简单的例子来说明问题。

本例中我们会定义如下类:

  1. PersonService类,给上层提供Person相关操作
  2. PersonDao类,给PersonService类提供DAO方法
  3. Person类,定义Person相关属性,是一个POJO
  4. App类,入口类,调用注解注入的PersonService类

PersonService类实现如下:

package cn.outofmemory.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonService {

    @Autowired
    private PersonDao personDao;
    
    public Person getPerson(int id) {
        return personDao.selectPersonById(id);
    }
}

在Service类上使用了@Service注解修饰,在它的私有字段PersonDao上面有@Autowired注解修饰。@Service告诉spring容器,这是一个Service类,默认情况会自动加载它到spring容器里。而@Autowired注解告诉spring,这个字段是需要自动注入的。

PersonDao类:

package cn.outofmemory.spring;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

@Scope("singleton")
@Repository
public class PersonDao {

    public Person selectPersonById(int id) {
        Person p = new Person();
        p.setId(id);
        p.setName("Person name");
        return p;
    }
}

在PersonDao类上面有两个注解,分别为@Scope和@Repository,前者指定此spring bean的scope是单例,你也可以根据需要将此bean指定为prototype,@Repository注解指定此类是一个容器类,是DA层类的实现。这个类我们只是简单的定义了一个selectPersonById方法,该方法的实现也是一个假的实现,只是声明了一个Person的新实例,然后设置了属性,返回他,在实际应用中DA层的类肯定是要从数据库或者其他存储中取数据的。

Person类:

package cn.outofmemory.spring;

public class Person {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Person类是一个POJO。

App类:

package cn.outofmemory.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Hello spring! from outofmemory.cn
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml");
        PersonService service = appContext.getBean(PersonService.class);
        Person p = service.getPerson(1);
        System.out.println(p.getName());
    }
}

在App类的main方法中,我们初始化了ApplicationContext,然后从中得到我们注解注入的PersonService类,然后调用此对象的getPerson方法,并输出返回结果的name属性。

注解注入也必须在spring的配置文件中做配置,我们看下spring.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"
       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-3.0.xsd">
    <context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false">
        <context:include-filter type="regex" expression="cn\.outofmemory\.spring\.[^.]+(Dao|Service)"/>
     </context:component-scan>
</beans>

这个配置文件中必须声明xmlns:context 这个xml命名空间,在schemaLocation中需要指定schema:

 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd

 

这个文件中beans根节点下只有一个context:component-scan节点,此节点有两个属性base-package属性告诉spring要扫描的包,use-default-filters="false"表示不要使用默认的过滤器,此处的默认过滤器,会扫描包含Service,Component,Repository,Controller注解修饰的类,而此处我们处于示例的目的,故意将use-default-filters属性设置成了false。

context:component-scan节点允许有两个子节点<context:include-filter>和<context:exclude-filter>。filter标签的type和表达式说明如下:

Filter TypeExamples ExpressionDescription
annotationorg.example.SomeAnnotation符合SomeAnnoation的target class
assignableorg.example.SomeClass指定class或interface的全名
aspectjorg.example..*Service+AspectJ語法
regexorg\.example\.Default.*Regelar Expression
customorg.example.MyTypeFilterSpring3新增自訂Type,實作org.springframework.core.type.TypeFilter

在我们的示例中,将filter的type设置成了正则表达式,regex,注意在正则里面.表示所有字符,而\.才表示真正的.字符。我们的正则表示以Dao或者Service结束的类。

我们也可以使用annotaion来限定,如下:

<?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.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>

</beans>

这里我们指定的include-filter的type是annotation,expression则是注解类的全名。

另外context:conponent-scan节点还有<context:exclude-filter>可以用来指定要排除的类,其用法和include-filter一致。

最后我们要看下输出的结果了,运行App类,输出:

2014-5-18 21:14:18 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1cac6db: startup date [Sun May 18 21:14:18 CST 2014]; root of context hierarchy
2014-5-18 21:14:18 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring.xml]
2014-5-18 21:14:18 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1fcf790: defining beans [personDao,personService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor]; root of factory hierarchy
Person name

前几行都是spring输出的一些调试信息,最后一行是我们自己程序的输出。

 

实验十二 SpringMVC 一、实验目的 1、掌握SpringMVC项目构建 2、掌握SpringMVC数据接收与传递的原理 二、实验过程 1、配置SpringMVC开发环境 a)创建新的项目,TestSpringMvc b)为项目添加Web框架和SpringMVC框架 c)添加classes目录 d)添加javaee依赖 e)添加lib输出配置 将依赖文件添加至lib中 f)修改web.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"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> <filter> <filter-name>charactorEncoding</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>charactorEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> g)修改applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <context:annotation-config></context:annotation-config> <context:component-scan base-package="cs18.controller"/> </beans> h)添加controller,TestController.java @Controller public class TestController { @RequestMapping(value = "/showName") public String showName(HttpServletRequest request, HttpServletResponse response) { //访问传递的参数 ; return "index.jsp"; } } i)配置tomcat,添加项目部署 j)启动tomcat,在浏览器中输入以下地址 http://localhost:8080/TestSpringMvc/showName?name=fredy 2、测试以下不同类型数据绑定方法 a)HttpServletRequet,HttpSession,Model/ModelMap b)简单数据类型绑定(int,String等) c)POJO数据绑定 d)包装POJO数据绑定 e)自定义数据类型绑定 f)数组或集合绑定 g)使用Json风格类型的数据绑定
06-11
创建Web项目,导入相关JAR包; <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> 创建并配置web.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"> <servlet> <servlet-name>Springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:SpringMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 添加用于上传的jsp页面; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>文件上传</title> </head> <body> <table border="1"> <tr> <td width="500" align="center">文件上传</td> </tr> <tr> <td> <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploadfiles" multiple="multiple"/><br> <input type="submit" value="上传"><br> </form> </td> </tr> <c:forEach items="${msgs}" var="msg"> <tr><td align="center" colspan="2" style="color: red">${msg}</td></tr> </c:forEach> </table> </body> </html> 创建控制类用于上传文件; package com.springmvc.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/file") public class FileUploadController { @RequestMapping("/upload") public String fileUpload(ArrayList<MultipartFile> uploadfiles, HttpServletRequest request) { //定义列表msgs保存提示信息 ArrayList<String> msgs = new ArrayList<>(); if (uploadfiles.get(0).getSize() > 0) { //判断是否上传文件 for (MultipartFile file : uploadfiles) { //循环获取文件 //判断文件不为空且大小大于0 if (!file.isEmpty() & file.getSize() > 0) { //获取文件原始名称 String originalFilename = file.getOriginalFilename(); //获取服务器中的文件夹路径 String path = request.getServletContext().getRealPath("/upload/"); //设置文件保存到服务器的目标路径 String filePath = path + originalFilename; try { //保存文件内容到目标路径 file.transferTo(new File(filePath)); } catch (IOException e) { msgs.add(filePath + "保存失败"); } msgs.add(filePath +"保存成功"); } } } else msgs.add("上传文件失败"); request.setAttribute("msgs", msgs); return "fileUpload"; } } 添加配置文件; <?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.springmvc.controller"/> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--配置视图控制器,指定文件上传页面的映射路径--> <mvc:view-controller path="/file/fileupload" view-name="fileUpload"/> <mvc:view-controller path="/file/filedownload" view-name="fileDownload"/> <!--配置注解驱动--> <mvc:annotation-driven/> <!--配置文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--指定请求的编码方式--> <property name="defaultEncoding" value="UTF-8"></property> <!--指定允许上传文件的大小,此处设置最大值为1 M,单位为字节--> <property name="maxUploadSize" value="1024000"></property> </bean> </beans> 添加上传成功的消息页面。 文件下载: 创建控制器类: package com.springmvc.controller; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/file") public class FileDownloadController { @RequestMapping("/download") public ResponseEntity<byte[]> FileDownload(HttpServletRequest request, String fileName) throws IOException { //获取下载文件的路径 String filepath = request.getServletContext().getRealPath("/upload/") + fileName; //创建该文件的对象 File file = new File(filepath); //将文件读取到字节数组中 byte[] bytes = FileUtils.readFileToByteArray(file); //创建HttpHeaders对象设置响应头信息 HttpHeaders headers = new HttpHeaders(); //设置浏览器以“UTF-8”编码方式显示文件名 fileName = URLEncoder.encode(fileName, "UTF-8"); //设置以下载的方式打开文件,并指定文件名称 headers.setContentDispositionFormData("attachment", fileName); //设置文件的下载方式为二进制流 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } } 添加用于上传的jsp页面; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>文件下载</title> </head> <body> <table border="1"> <tr> <td width="350" align="center">下载列表</td> </tr> <tr> <td> <a href="${pageContext.request.contextPath}/file/download?fileName=微信图片_20250612231528.jpg"> 这是一张图片</a><br> </td> </tr> </table> </body> </html> 实验成果: 修改一下
11-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值