【译】Spring 4 自动装配、自动检测、组件扫描示例

简介:

在本篇文章我们会看到Spring是如何通过component-scanning配置,在没有使用@Bean和@Configuration声明bean,也没有使用XML配置声明bean的情况下,自动检测到程序中配置的bean,并且自动装配这些bean。

对于component-scanning的配置,本文将使用@ComponentScan注解,当然,我们也会提供一份对应的XML配置来作为比较。

我们将创建一个典型的企业级应用示例,涉及不同的层(Service、DAO)。

涉及的技术及开发工具

  • Spring 4.0.6.RELEASE
  • Joda-time 2.3
  • Maven 3
  • JDK 1.6
  • Eclipse JUNO Service Release 2

工程结构目录

如下是本工程的目录结构

接下来开始往上面添加具体内容。

步骤一:往pom.xml添加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.websystique.spring</groupId>
  <artifactId>Spring4AutoScanning</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>
 
  <name>Spring4AutoScanning</name>
    <properties>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <joda-time.version>2.3</joda-time.version>
    </properties>
 
    <dependencies>
        <!--  Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
 
        <!-- Joda-Time -->       
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${joda-time.version}</version>
        </dependency>
 
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
 
</project>
复制代码

这个示例,我们使用了Spring-core和Spring-context依赖,另外,还使用了JodaTime的LocalDate类来做一些日期计算,所以引入了joda-time依赖。

步骤二:创建Spring配置类

Spring配置类是用@Configuration注解标注的,这些类包含了用@Bean注解标注的方法,这些方法生成bean会交给Spring容器来管理。

复制代码
package com.websystique.spring.configuration;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan(basePackages = "com.websystique.spring")
public class AppConfig {
 
}
复制代码

你可能注意到上面的类是空的,没有使用@Bean标注的方法,那么bean从哪里产生呢?

事实上,我们使用了@ComponentScan注解,来帮助我们自动检测bean

@ComponentScan(basePackages = "com.websystique.spring")

@ComponentScan注解的basePackages属性是一个包名,配置好后,将会在该包下查找所有使用特定注解标注的类,作为bean。

如下是一些常见的注解,被这些注解标注的类是一个bean,将会被自动检测

@Repository - 作为持久层的DAO组件.
@Service - 作为业务层的Service组件.
@Controller - 作为展现层的Controller组件.
@Configuration - Configuration组件.
@Component - 通用注解, 可以作为以上注解的替代.

注意上面的注解内部都是用@Component标注的,所以实际上你可以在任何地方使用@Component, 但是为了表达更加清晰的设计意图,强烈建议根据不同情况使用不同的注解。

注意:在我们这里例子,你甚至可以直接删除配置类因为它并没有包含任何@Bean注解标注的方法,在后面的main方法里我们将会看到在这种情况下是如何扫描这些Bean。

另外,看下使用XML配置的情况,结果如下(命名为app-config.xml)

复制代码
<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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  
    <context:component-scan base-package="com.websystique.spring" />
  
</beans>
复制代码

步骤三:创建DAO层的类

复制代码
package com.websystique.spring.dao;
 
import com.websystique.spring.model.Employee;
 
public interface EmployeeDao {
 
    void saveInDatabase(Employee employee);
}
复制代码
复制代码
package com.websystique.spring.dao;
 
import org.springframework.stereotype.Repository;
 
import com.websystique.spring.model.Employee;
 
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao{
 
    public void saveInDatabase(Employee employee) {
 
        /*
         * Logic to save in DB goes here
         */
        System.out.println("Employee "+employee.getName()+" is registered for assessment on "+ employee.getAssessmentDate());
         
    }
 
}
复制代码

@Repository注解标注该类作为一个持久层自动检测的bean,参数employeeDao为bean提供了一个名字,我们将会在主服务Bean里注入该bean。

步骤四:创建Service层类

复制代码
package com.websystique.spring.service;
 
import org.joda.time.LocalDate;
 
public interface DateService {
 
    LocalDate getNextAssessmentDate();
}
复制代码
复制代码
package com.websystique.spring.service;
 
import org.joda.time.LocalDate;
import org.springframework.stereotype.Service;
 
@Service("dateService")
public class DateServiceImpl implements DateService{
 
    public LocalDate getNextAssessmentDate() {
        return new LocalDate(2015,10,10);
    }
 
}
复制代码

@Service注解标注这个类为业务层自动检测的bean,后续我们会将其注入到主服务bean中。

复制代码
package com.websystique.spring.service;
 
import com.websystique.spring.model.Employee;
 
public interface EmployeeService {
 
    void registerEmployee(Employee employee);
}
复制代码
复制代码
package com.websystique.spring.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.websystique.spring.dao.EmployeeDao;
import com.websystique.spring.model.Employee;
 
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
 
    @Autowired
    private DateService dateService;
     
    @Autowired
    private EmployeeDao employeeDao;
     
 
    public void registerEmployee(Employee employee) {
        employee.setAssessmentDate(dateService.getNextAssessmentDate());
        employeeDao.saveInDatabase(employee);
    }
     
}
复制代码

EmployeeService是我们的主服务类,可以看到,我们往这个类注入了DateService和EmployeeDao。被@Autowired注解标注的dateService属性,会被Spring的依赖注入自动装配合适的Bean,由于我们已经使用@Service声明了一个DateService Bean,所以该Bean将会被注入到这里。类似的,被@Repository标注的EmployeeDao也会被注入到employeeDao属性中。

如下是我们的实体类Employee

复制代码
package com.websystique.spring.model;
 
import org.joda.time.LocalDate;
 
public class Employee {
 
    private int id;
 
    private String name;
 
    private LocalDate assessmentDate;
 
    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;
    }
 
    public LocalDate getAssessmentDate() {
        return assessmentDate;
    }
 
    public void setAssessmentDate(LocalDate assessmentDate) {
        this.assessmentDate = assessmentDate;
    }
 
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", assessmentDate="
                + assessmentDate + "]";
    }
 
}
复制代码

步骤五:创建main方法运行该程序

复制代码
package com.websystique.spring;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
 
import com.websystique.spring.configuration.AppConfig;
import com.websystique.spring.model.Employee;
import com.websystique.spring.service.EmployeeService;
 
public class AppMain {
 
    public static void main(String args[]){
        AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
         
        EmployeeService service = (EmployeeService) context.getBean("employeeService");
 
        /*
         * Register employee using service
         */
        Employee employee = new Employee();
        employee.setName("Danny Theys");
        service.registerEmployee(employee);
         
        context.close();
    }
}
复制代码

运行上面的程序,会看到如下结果:

Employee Danny Theys is registered for assessment on 2016-12-22

另外,假如你想不使用配置类AppConfig,那么还可以这样做:

复制代码
package com.websystique.spring;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import com.websystique.spring.model.Employee;
import com.websystique.spring.service.EmployeeService;
 
public class AppMain {
 
    public static void main(String args[]){
        //AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
        AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext();
        context.scan("com.websystique.spring"); 
        context.refresh();
 
        EmployeeService service = (EmployeeService) context.getBean("employeeService");
 
        /*
         * Register employee using service
         */
        Employee employee = new Employee();
        employee.setName("Danny Theys");
        service.registerEmployee(employee);
         
        context.close();
    }
}
复制代码

AnnotationConfigApplicationContext.scan方法会扫描指定包下的所有类,注册所有被@Component标注的bean(实际上@configuration本身内部也是使用@component注解)到应用的上下文环境中;

另外要注意,在完成扫描操作后,refresh方法必须被调用,能保证完整的处理这些注册类。

运行以上程序,你会看到同样的输出。

最后,如果使用XML配置的话,在main方法里替换

AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);

为

AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");

会看到同样的输出。


本文转自风一样的码农博客园博客,原文链接:http://www.cnblogs.com/chenpi/p/6211410.html,如需转载请自行联系原作者

相关文章
|
NoSQL 安全 Java
深入理解 RedisConnectionFactory:Spring Data Redis 的核心组件
在 Spring Data Redis 中,`RedisConnectionFactory` 是核心组件,负责创建和管理与 Redis 的连接。它支持单机、集群及哨兵等多种模式,为上层组件(如 `RedisTemplate`)提供连接抽象。Spring 提供了 Lettuce 和 Jedis 两种主要实现,其中 Lettuce 因其线程安全和高性能特性被广泛推荐。通过手动配置或 Spring Boot 自动化配置,开发者可轻松集成 Redis,提升应用性能与扩展性。本文深入解析其作用、实现方式及常见问题解决方法,助你高效使用 Redis。
1698 4
|
负载均衡 Java Nacos
Spring Cloud五大组件
Spring Cloud五大组件
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
628 0
|
安全 Java 决策智能
Spring Boot自动装配
Spring Boot自动装配基于“约定优于配置”理念,通过条件化配置与Starters机制,智能推断并加载所需组件,大幅简化开发流程。它实现配置自动化,提升效率,降低维护成本,支持自定义扩展,推动微服务快速构建,是Java生态中开发范式的革新之作。(238字)
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1068 2
|
安全 数据可视化 Java
AiPy开发的 Spring 漏洞检测神器,未授权访问无所遁形
针对Spring站点未授权访问问题,现有工具难以检测如Swagger、Actuator等组件漏洞,且缺乏修复建议。全新AI工具基于Aipy开发,具备图形界面,支持一键扫描常见Spring组件,自动识别未授权访问风险,按漏洞类型标注并提供修复方案,扫描结果可视化展示,支持导出报告,大幅提升渗透测试与漏洞定位效率。
|
Java Spring
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
869 73
|
JSON 前端开发 Java
Spring MVC 核心组件与请求处理机制详解
本文解析了 Spring MVC 的核心组件及请求流程,核心组件包括 DispatcherServlet(中央调度)、HandlerMapping(URL 匹配处理器)、HandlerAdapter(执行处理器)、Handler(业务方法)、ViewResolver(视图解析),其中仅 Handler 需开发者实现。 详细描述了请求执行的 7 步流程:请求到达 DispatcherServlet 后,经映射器、适配器找到并执行处理器,再通过视图解析器渲染视图(前后端分离下视图解析可省略)。 介绍了拦截器的使用(实现 HandlerInterceptor 接口 + 配置类)及与过滤器的区别
1530 0
|
负载均衡 算法 Java
除了 Ribbon,Spring Cloud 中还有哪些负载均衡组件?
这些负载均衡组件各有特点,在不同的场景和需求下,可以根据项目的具体情况选择合适的负载均衡组件来实现高效、稳定的服务调用。
1698 61